mongodb - perform batch query

后端 未结 2 845
孤街浪徒
孤街浪徒 2021-02-13 20:46

I need query data from collection a first, then according to those data, query from collection b. Such as:

For each id queried from a
    query data from b where         


        
相关标签:
2条回答
  • 2021-02-13 21:11

    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.

    0 讨论(0)
  • 2021-02-13 21:17

    You'll need to do it as two steps.

    Look into the $in operator (reference) which allows passing an array of _ids for example. Many would suggest you do those in batches of, say, 1000 _ids.

    db.myCollection.find({ _id : { $in : [ 1, 2, 3, 4] }})
    
    0 讨论(0)
提交回复
热议问题