Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I know MongoDB is able to handle a lot of requests/sec, but let's say I have to query a lot of documents of a collection given their _id; what sounds better: making a $in on the _id attribute with all the ids I want to get, or loop over findOne queries?

2 Answers

0 votes
by (106k points)

The upper hand is with the $in query and providing an array of _ids.

Example:

db.collection.find({ 

"key": { 

"$in": [ 

ObjectId("xxx"), 

ObjectId("yyy"), 

ObjectId("zzz") 

})

0 votes
by (108k points)

$in returns a boolean indicating whether a specified value is in an array.

$in has the following operator expression syntax:

{ $in: [ &lt;expression&gt;, <array expression> ] }

If you loop, there is some amount of setup and teardown for each query creating and exhausting cursors which would create overhead.

If you are not performing this on a local machine it also creates TCP/IP overhead for every request. Locally you could use domain sockets.

There is an index on "_id" generated by default and assembling a group of documents to return in a batch request should be extremely fast so there is no need to break this up into smaller queries.

Related questions

0 votes
2 answers
asked Oct 18, 2019 in Web Technology by Sammy (47.6k points)
0 votes
1 answer
asked Jan 5, 2020 in Web Technology by ashely (50.2k points)
0 votes
1 answer
asked Oct 18, 2019 in Web Technology by Sammy (47.6k points)
0 votes
1 answer
asked Sep 9, 2019 in SQL by Sammy (47.6k points)

Browse Categories

...