Монго, как обновить поле, если последний элемент другого массива соответствует критериям - PullRequest
0 голосов
/ 02 июня 2018

У меня есть документы типа

{
'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'}
]
}

Длина массива не фиксирована, я хочу проверить поле 'check' последнего элемента.Если оно больше 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 голосов
/ 03 июня 2018

попробуйте этот запрос для обновления же

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(); }
...