Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb - perform batch query

Tags:

mongodb

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 "_id" == id

In SQL, this can be done by join table a & b in a single select. But in mongodb, it needs do multi query, it seems inefficient, doesn't it? Or it can be done by just 2 queries?(one for a, another for b, rather than 1 plus n) I know NoSQL doesn't support join, but is there a way to batch execute queries in for loop into a single query?

like image 666
jean Avatar asked Feb 09 '14 16:02

jean


People also ask

What is batch insert in MongoDB?

Multiple documents can be inserted at a time in MongoDB using bulk insert operation where an array of documents is passed to the insert method as parameter.

What is Batchsize in MongoDB?

Specifies the number of documents to return in each batch of the response from the MongoDB instance. In most cases, modifying the batch size will not affect the user or the application, as mongosh and most drivers return results as if MongoDB returned a single batch.


1 Answers

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] }})
like image 73
WiredPrairie Avatar answered Oct 06 '22 09:10

WiredPrairie