【问题标题】:Create GeoJson from coordinates array in the same Mongodb collection从同一 Mongodb 集合中的坐标数组创建 GeoJson
【发布时间】:2016-04-26 15:16:54
【问题描述】:

我想将我的 mongodb 集合从 2d 修改为 2dsphere。 我的 db.users 中有这个结构:

{
  "_id" : "1c6930387123e960eecd65e8ade28488",
  "interests" : [
     {
       "_id" : ObjectId("56a8b2a72f2c2a4c0250e896"),
       "coordinates" : [-3.6833, 40.4]
    }
  ],   
}

我想要这样的东西:

{
  "_id" : "1c6930387123e960eecd65e8ade28488",
  "interests" : [
     {
       "_id" : ObjectId("56a8b2a72f2c2a4c0250e896"),
       "loc":{
         "type":"Point",
         "coordinates" : [-3.6833, 40.4]
       }
    }
  ],   
}

我试过了:

db.users.update( {interests:{$elemMatch:{coordinates :  { $exists: true } }}}, { $set: { 'interests.$.place':{"type":"Point", "coordinates":'interests.$.coordinates'} } }, { upsert: false, multi: false });

显然,它插入字面意思是“'interests.$.coordinates'

并在 Node 中尝试过:

users.find({interests:{$elemMatch:
    {coordinates :  
        { $exists: true } }}} ,
    {"interests.coordinates":1,"interests._id":1,"_id":0 }).forEach( function( doc ){
        users.update( {interests:
            {$elemMatch:
                {_id :  doc.interests[0]['_id'] }}}, 
            { $set: { 'interests.$.loc':{"type":"Point", "coordinates":doc.interests[0]['coordinates']} } }, 
            { upsert: false, multi: false },function(err, numberAffected, rawResponse) {
            var modified=numberAffected.result.nModified;
             console.log(modified)
        });
    });

但是坐标被插入了混合值。

想法?

谢谢!!

【问题讨论】:

    标签: node.js mongodb geojson 2dsphere


    【解决方案1】:

    我没有测试这段代码,但我认为这会阐明这个问题。

    users.find(
        {interests:{ $elemMatch: {coordinates : { $exists: true } }}}).forEach( function( doc ){
    
            for(var c = 0; c < doc.interests.length; c++) {
    
                var orig = doc.interests[c].coordinates;
                doc.interests[c].loc: { type:"Point", coordinates: orig };
                //delete doc.interests[c].coordinates;
    
            };
    
            users.update({ _id: doc._id }, doc);
        });
    

    尝试遍历集合中的所有文档,修改整个文档,然后在一行中更新它。

    警告:如果您的集合中有大量符合“查找”条件的文档,则应使用分页(跳过/限制)以避免首次加载时出现性能和内存问题。

    【讨论】:

    • 你太棒了!!您的代码工作正常!只有我必须将这个“doc.interests.coordinates.length”修改为这个“doc.interests.length”,并且效果很好!非常感谢!
    • 谢谢!我修正了那个打字错误!
    猜你喜欢
    • 2021-12-16
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 2021-07-13
    • 2015-05-28
    • 2020-09-22
    相关资源
    最近更新 更多