Query optimization loop

Is there any better way to optimize below query.

var List = ['XXXXXXXXX','XXXXXXXX','XXXXXXX','XXXXXXX','XXXXX'];
for (var i = 0; i < List.length; i++) {
    var lst = List[i];
    try {
        db.getCollection('XXX').find({
            XXX: lst,
            XXX: 'XXX',
            XXX:'XXX'
        }).forEach(
            function (cyuDoc) {
                db.getCollection('cyuquestion')
                .updateMany({
                    XXX: lst,
                    XXX: 'XXX',
                    'XXXX' : cyuDoc._id.valueOf()
                }, {
                    $set: {
                        XXXX: 'XXX'
                    }
                });
            })
    printjson(`${lst} : Success`)
    } catch (e) {
        printjson(`${lst} : Error Found`)
        printjson("ERR:: " + e);
    }
}

Hello @A_W,

It is hard to understand your query because of unclear fields/key names or different collections, can you please add an example document and the expected behavior that you wanted to perform, little bit of explanation would be good to understand the question.

As a prediction, you can avoid for loop and use use $in operator to check your list of values in the find query.

1 Like

As said above, use an $in and package up the updates into a bulk update so you just make one server call.

/edit typo from phone corrected