2017-04-11 19 views
0

我有如下文檔。我想要做的是取消設置ID,並保持每個文檔的_id。從mongdb中的文檔取消設置ID字段

"educations": [ 
{ 
    "_id": ObjectId("58ec7aaaa3c19b8793805cca00e"), 
    "school": "xyz", 
    "type": "pqr", 
    "updatedAt": ISODate("2017-04-11T06:36:03.588Z"), 
    "createdAt": ISODate("2015-03-05T12:32:26.735Z"), 
    "obj_type": "education", 
    "current": false 
}, 
{ 
    "_id": ObjectId("58eceeeee353c19b673805cca00f"), 
    "school": "KTH", 
    "type": "tun", 
    "updatedAt": ISODate("2017-04-11T06:36:03.588Z"), 
    "createdAt": ISODate("2015-02-16T23:17:12.393Z"), 
    "obj_type": "education", 
    "id": ObjectId("574eassssh83cbee22336d2d4"), 
    "current": false 
}, 
{ 
    "createdAt": ISODate("2016-08-19T07:31:12.640Z"), 
    "updatedAt": ISODate("2016-08-19T07:31:12.640Z"), 
    "type": "abc", 
    "school": "KTH", 
    "duration": "3+ år", 
    "_id": ObjectId("57bsssss687dfec6716dd75"), 
    "current": false 
} 

]

var query = { 
      $unset: {} 
      }; 
query.$unset['profile.educations.'+index+'.id'] = 1; 
models.User.update({_id: user._id},query, function(err, val){ 
     //some operation 
}); 

我做了什麼錯在這裏?有些建議值得高度讚賞。它可以在mongo控制檯中使用相同的查詢刪除它。

+0

您的文檔似乎不具備嵌入式一個'profile'根密鑰subdocument''profile.educations。'+ index +'。id'',你可能是指'教育'。+ index +'。id''? – chridam

+0

@chridam它最初的配置文件的子文檔 – Bikash

+0

你可以顯示完整的文檔結構,即'User'模型的模式定義嗎? – chridam

回答

0

您可以使用這樣的代碼:

db.collection.find({ 
     educations: { 
      $exists: true 
     } 
    }).forEach(function(myDoc) { 
     var child = myDoc.educations; 
     for (var i = 0; i < child.length; i++) { 
      var ob = child[i]; 
      if ('id' in ob) { 
       delete ob.id; 
       child[i] = ob; 
      } 
     }db.collection.update({ 
      _id: myDoc._id 
     }, { 
      $set: { 
       educations: child 
      } 
     }); 
     printjson(myDoc); 
    }); 

(OR) 你試試這其中也,

db.collection.update({ 
    "educations.id": {$exists: true} 
},{ 
    $unset: { 
     "educations.$.id" : true 
    } 
},false,true) 
+0

@Bikash,你需要檢查這也.. –

+0

它沒有幫助 – Bikash

相關問題