mongodb - perform batch query
It's very simple, don't make so many DB calls for each id, it is very inefficient, it is possible to execute a single query which will return all documents relevant to each of the ids in a single pass using the $in operator in MongoDB, which is synonymous to in syntax in SQL so for example if you need to find out the documents for 5 ids in a single pass then
const ids = ['id1', 'id2', 'id3', 'id4', 'id5'];
const results = db.collectionName.find({ _id : { $in : ids }})
This will get you all the relevant documents in a single pass.
You'll need to do it as two steps.
Look into the $in
operator (reference) which allows passing an array of _id
s for example. Many would suggest you do those in batches of, say, 1000 _id
s.
db.myCollection.find({ _id : { $in : [ 1, 2, 3, 4] }})