Mongo如果另一个数组的最后一个元素符合条件,如何更新字段

时间:2018-06-01 21:34:54

标签: mongodb mongodb-query mongodb-update

我有像

这样的文件
{
'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'}
]
}

数组长度不固定,我想检查最后一个元素' s'检查'领域。如果它大于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'}
]
}

1 个答案:

答案 0 :(得分: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(); }