2016-04-26 114 views
1

我想将我的mongodb集合从2d修改为2dsphere。 我有这个结构在我db.users:从同一个Mongodb集合中坐标数组创建GeoJson

{ 
    "_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 }); 

很明显,它直接插入“'interest。$。坐标

并试图在这个节点:

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) 
     }); 
    }); 

但坐标插入混合值。

想法?

谢谢!

回答

0

我没有测试这段代码,但我认为这将揭示这个问题。

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); 
    }); 

尝试迭代集合中的所有文档,修改整个文档,然后在一行中进行更新。

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

+0

你真了不起! 你的代码工作正常! 只有我不得不将这个“doc.interests.coordinates.length”修改为这个“doc.interests.length”并且它非常完美! 非常感谢! –

+0

谢谢!我修正了那个输入错误! – Findemor