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?
Asked
Active
Viewed 5.6k times
2 Answers
58
I would definitely go with using the $in query and providing a array of _ids.
Example:
db.collection.find({
"key": {
"$in": [
ObjectId("xxx"),
ObjectId("yyy"),
ObjectId("zzz")
]
}
})
Why?
- If you loop, there is a certain amount of setup and teardown for each query creating and exhausting cursors which would create overhead.
- If you are not doing this on a local machine it also creates tcp/ip overhead for every request. Locally you could use domain sockets.
- There is a index on "_id" created by default and collecting 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.
There's some additional documentation here if you want to check it out.

Tyler Brock
- 29,626
- 15
- 79
- 79
-
8What if there's a lot of items in the $in... say 100, or 1,000? – ewindsor Feb 15 '12 at 18:40
-
@ewindsor anything up to 1000 is usually ok. After that i'd reconsider the schema you have and start pre-computing the data. – Tyler Brock Jul 22 '13 at 14:46
-
2can `$in` be used on an array of JSON objects? – Kevin Meredith Oct 02 '13 at 19:49
-
Actually limit can be very high(even upto a million), but mainly depends upon the size: https://stackoverflow.com/questions/5331549/what-is-the-maximum-number-of-parameters-passed-to-in-query-in-mongodb – JavaTec Mar 05 '21 at 15:33
0
If You want to find directly with MongoChef UI you can use this query:
Field:{$in:[/Naveen Kumar/i, /Naveen/i, /Garshakurthy/i]}}

Nawin
- 485
- 8
- 14