1

我有像这样的文件

{
'need_to_update': 'not_update_yet',
'array' : [
     {'check' : 1, 'other': 'not_related'},
     {'check' : 3, 'other': 'not_related'}
]
}

{
'need_to_update': 'not_update_yet',
'array' : [
     {'check' : 1, 'other': 'not_related'},
     {'check' : 3, 'other': 'not_related'},
     {'check' : 20, 'other': 'not_related'}
]
}

数组长度不固定,我想检查最后一个元素的“检查”字段。如果大于 10,我需要更新文档的“need_to_update”。希望我的描述不会造成任何误解。

所以例子中只更新了第二个文档,更新后的文档应该是:

{
'need_to_update': 'not_update_yet',
'array' : [
     {'check' : 1, 'other': 'not_related'},
     {'check' : 3, 'other': 'not_related'}
]
}

{
'need_to_update': 'updated',
'array' : [
     {'check' : 1, 'other': 'not_related'},
     {'check' : 3, 'other': 'not_related'},
     {'check' : 20, 'other': 'not_related'}
]
}
4

1 回答 1

0

试试这个查询更新相同

var bulk = db.collection.initializeUnorderedBulkOp(),
counter = 0;
db.collection.find({}).forEach(
    function(doc) {
      var array = doc.array;
      if (array != null && array != undefined) {
        var lastObj = array[array.length - 1];
        var check = lastObj.check;
        bulk.find( { "array.check": check } ).update( { $set: { "need_to_update": "updated" } } );
        counter++;
    if (counter % 1000 == 0) {
        bulk.execute();
        bulk = db.collection.initializeUnorderedBulkOp();
    }
      }
    }
);
if (counter % 1000 != 0) { bulk.execute(); }
于 2018-06-03T19:21:45.990 回答