我的文件如下。我想要做的是取消设置id并从每个文档中保留_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 :(得分: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)