2016-04-26 113 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