MongoDB $in Performance with Large ObjectId Arrays
Benchmarks of MongoDB and Mongoose $in with 100 to 50,000 ObjectIds: index bounds, the 16 MB limit, the sort trap at 201 values and the batch size that won.
On this page 8 sections
I put one million orders in a local MongoDB, picked 50,000 of their _ids at random and ran a single find({ _id: { $in: ids } }) through Mongoose. It took about 190 ms. The server reported 113 ms of that, so roughly 80 ms went on the Node side: sending a 917 KB filter and decoding 50,000 documents.
That is the question behind most “mongoose find $in large array slow” searches. Somebody has a list of ids from a cache or another service, the list has grown from 50 to 5,000 to 50,000, and they want to know where it breaks. I ran the experiments instead of repeating the folklore. Some of it held up and some of it did not.

Quick answer
$inon an indexed field usesIXSCAN. Cost grows roughly linearly with the list: about 4 µs per id on my machine once the list passes a few thousand.- There is no fixed cap on the number of values. The cap is the 16 MiB BSON document size, which at about 20 bytes per ObjectId is roughly 840,000 ids on paper.
- Batching helps a little, and only if you run the batches in parallel. Sequential batches were slower than one big query.
- Sorting is the real trap. Up to 200 values MongoDB can merge index scans; at 201 a
SORTstage appears. - Deduplicating and pre-sorting the list changed nothing measurable. Casting strings changed correctness, not speed.
How the benchmark was set up
Everything below comes from one machine, so treat the numbers as shapes rather than promises.
- MongoDB 8.2.4, standalone, local, on an Apple M1 Pro with 16 GB of RAM
- Mongoose 9.13.2 with driver 7.9.1, Node 24
- 1,000,000
ordersdocuments, about 310 MB of data and 40 MB of indexes:customerId(ObjectId),status,total,createdAtand a 200-characternote - Indexes on
_id,{ customerId: 1, createdAt: -1 }and{ createdAt: -1 } - Warm cache and loopback networking, so no real network latency. Timings are the median of 7 runs.
How MongoDB executes $in under the hood
For { _id: { $in: ids } } the planner sorts and deduplicates the values and turns each one into a point interval on the _id index. The plan is FETCH > IXSCAN, and indexBounds in the explain output has one entry per value. Reading it in order, the scan jumps from one interval to the next instead of walking the index.
You can see the cost in totalKeysExamined. It came out at about twice the number of ids every time (97,588 for 50,000). My reading is one seek plus one key check per value, though I did not confirm that against the source. Either way it is proportional to the list, not to the collection size.
Because the server does the sorting and deduplication, doing them in Node first does not buy anything. I tried 50,000 ids in random order and the same ids sorted: 188 ms against 188 ms, then 183 against 178 on a second pass. That is inside the noise.
The 16 MB limit
A BSON document tops out at 16 MiB, and your filter is a BSON document. Each ObjectId inside an array costs 12 bytes for the value, one for the type, a few for the array index used as its key and a trailing null. Measured, that was about 20 bytes each, so 16 MiB holds around 840,000 of them.
I pushed past it. On this stack a filter of 896,093 ids (17.8 MB of BSON) went through. At 896,875 the Node driver threw a RangeError [ERR_OUT_OF_RANGE] from its serialiser, not the server-side “BSONObj size is invalid” error I expected. I did not dig into why the server accepted more than 16 MiB, and I would not plan around it. Older servers and drivers may stop you earlier, and by the time you are sending a 17 MB filter you have a design problem, not a limit problem.
Benchmark: 100 vs 1,000 vs 10,000 vs 50,000 ObjectIds
Single find({ _id: { $in: ids } }), ids sampled at random from the collection, every id exists.
| ObjectIds | Filter size | Server executionTimeMillis |
totalKeysExamined |
totalDocsExamined |
Mongoose .lean() |
Hydrated documents | Heap held by result |
|---|---|---|---|---|---|---|---|
| 100 | 2 KB | 3 ms | 200 | 100 | 1.3 ms | 1.2 ms | about 0 |
| 1,000 | 17 KB | 5 ms | 1,999 | 1,000 | 6.4 ms | 7.3 ms | 0.7 MB |
| 10,000 | 175 KB | 28 ms | 19,904 | 10,000 | 39.1 ms | 51.6 ms | 4.6 MB |
| 50,000 | 917 KB | 113 ms | 97,588 | 50,000 | 191.8 ms | 241.7 ms | 18.2 MB |
Going from 1,000 to 50,000 ids is 50 times the work and took about 30 times the wall-clock time. Past the first few thousand it is a straight line, so there is no cliff to fall off.
The gap between the server’s figure and the wall-clock figure widens with size. At 50,000 ids about 40% of the time was spent outside the server. Tuning indexes will not touch that part.
And memory: I expected .lean() to hold far less heap than hydrated documents. For this five-field schema it did not. After a forced GC, 50,000 lean results held 18.2 MB and hydrated ones 18.1 MB. The speed difference was real (21 to 24% faster from 10,000 ids up), the memory difference was not, at least here. Documents with virtuals, getters or big subdocuments may behave differently.
5 best practices for large $in queries in Mongoose
1. Batch the list, and run the batches in parallel
I split the same 50,000 ids into chunks and measured the total:
| Chunk size | Concurrent queries | Total time |
|---|---|---|
| 50,000 (no batching) | 1 | 197 ms |
| 10,000 | 1 | 221 ms |
| 5,000 | 1 | 218 ms |
| 1,000 | 1 | 273 ms |
| 1,000 | 4 | 150 ms |
| 1,000 | 8 | 129 ms |
| 500 | 4 | 140 ms |
| 250 | 4 | 132 ms |
| 100 | 4 | 134 ms |
Sequential batching lost every time, because each round trip adds fixed cost and the server was not being given any extra parallelism. Four to eight chunks in flight beat the single query by a quarter to a third, and chunk sizes from 100 to 1,000 landed within 15% of each other once concurrency was there.
So my starting point is 1,000 ids per chunk and 4 concurrent queries. Remember the caveat: this ran on loopback. Over a real network each round trip costs more, which pushes towards bigger chunks and fewer of them. Measure with your own latency.
The better reasons to batch are different from speed. A smaller filter stays well away from the size limit, one slow query does not hog a connection and per-request memory stays bounded.
Here is a helper. It dedupes, casts once, applies .lean() and an optional projection, and returns a Map so callers can restore the order they had.
import { Types } from 'mongoose';
import type { Model } from 'mongoose';
type IdLike = string | Types.ObjectId;
interface FindByIdsOptions {
chunkSize?: number;
concurrency?: number;
select?: string;
}
export async function findByIds<T extends { _id: Types.ObjectId }>(
model: Model<T>,
ids: Iterable<IdLike>,
{ chunkSize = 1000, concurrency = 4, select }: FindByIdsOptions = {}
): Promise<Map<string, T>> {
// Dedupe on the string form, then cast once.
const unique = [...new Set([...ids].map(String))].map((id) => new Types.ObjectId(id));
const chunks: Types.ObjectId[][] = [];
for (let i = 0; i < unique.length; i += chunkSize) {
chunks.push(unique.slice(i, i + chunkSize));
}
const found = new Map<string, T>();
let next = 0;
const worker = async () => {
while (next < chunks.length) {
const chunk = chunks[next++];
let query = model.find({ _id: { $in: chunk } });
if (select) query = query.select(select);
const docs = await query.lean<T[]>();
for (const doc of docs) found.set(String(doc._id), doc);
}
};
await Promise.all(Array.from({ length: Math.min(concurrency, chunks.length) }, worker));
return found;
}Call it with const orders = await findByIds(Order, idsFromCache, { select: 'status total' }), then map over your original id list and read from the Map. Order is not preserved across chunks, so do not rely on result order. I ran it against the benchmark collection with 5,100 inputs (100 of them duplicates) and got back 5,000 documents carrying only _id, status and total.
2. Use .lean() and a projection
On 10,000 ids: hydrated documents 48 ms, .lean() 38 ms, .lean() with .select('status total') 30 ms. Together that is about 37% off, and the projection also shrinks what travels over the wire. My earlier post on making Mongoose queries faster with lean covers what you give up (virtuals, getters, save()). For a read-only lookup by id, I would skip hydration every time.
3. Watch the sort: the 200-value line
This is the one that surprised me. With the compound index { customerId: 1, createdAt: -1 } I ran find({ customerId: { $in: ids } }).sort({ createdAt: -1 }).limit(50) and varied the list size:
customerId values |
Winning plan |
|---|---|
| 100 | LIMIT > FETCH > SORT_MERGE > IXSCAN |
| 199 | LIMIT > FETCH > SORT_MERGE > IXSCAN |
| 200 | LIMIT > FETCH > SORT_MERGE > IXSCAN |
| 201 | FETCH > SORT > IXSCAN |
| 250 | FETCH > SORT > IXSCAN |
Up to 200 values, MongoDB treats the $in like that many equalities, runs one index scan per value and merges them in createdAt order. No sort stage, which is exactly what the ESR rule (equality, sort, range) promises. At 201 it gives up on that and falls back to a blocking SORT. The 200 matches what I believe is the default of internalQueryMaxScansToExplode, though I only verified the behaviour, not the parameter.
How bad is the SORT stage? With limit(50) and the sort key inside the index, it was cheap: the server sorted index keys and fetched only 50 documents (13 ms at 250 values, 34 ms at 1,000). The painful case is sorting on a field the index does not cover. Sorting 10,000 customers’ orders by total, with no limit, gave SORT > FETCH > IXSCAN, fetched 10,000 documents and sorted 3.3 MB in memory in 33 ms. Still fine, since usedDisk was false. Scale that to a few hundred thousand documents and you are into the blocking-sort memory limit (100 MB in the versions I know, but check yours). Put the sort field in the index, add a limit, or sort in application code if the result is small.
4. Cast strings to ObjectId, and dedupe for tidiness
Ids from a cache or a JSON payload arrive as strings. Mongoose’s find() casts them for you. Nothing else does:
| Query | Strings passed | Documents returned |
|---|---|---|
Order.find({ _id: { $in: strs } }) |
1,000 | 1,000 |
Order.collection.find(...) (native driver) |
1,000 | 0 |
Order.aggregate([{ $match: { _id: { $in: strs } } }]) |
1,000 | 0 |
aggregate() with new Types.ObjectId(s) |
1,000 | 1,000 |
No error and no warning, just an empty array. If you move a query from find() to an aggregation pipeline, cast the ids yourself.
On deduplication, I expected a speed-up and did not get one. With 50,000 unique ids plus 25,000 duplicates the query ran in 216 ms as strings, 214 ms deduped and 212 ms deduped and cast manually. The server examined 97,588 keys in all three cases, so it was already ignoring the duplicates. What new Set() saves is bytes on the wire, about half a megabyte here. Cheap, so do it, but do not expect it to fix a slow query.
5. Know when $in is the wrong tool
I did not benchmark this part, so take it as design advice, not measurement. If the same list of ids keeps coming back (a segment, a campaign audience, a saved selection), the list is data and belongs in the database. Two options:
- Store membership on the documents, for example
segmentIds: [ObjectId]with a multikey index, and query{ segmentIds: segmentId }. One value, one index lookup. - Write the ids to a temporary collection and join with
$lookup. This helps when the list is large and one-off, and aggregation pipeline performance matters much more at that point, because an unindexed$lookupwill punish you.
If the list changes on every request and is under a few thousand ids, a plain $in is fine. I would not redesign a schema for that.
Inspect your $in query with explain("executionStats")
In Mongoose:
const ex = await Order.find({ _id: { $in: ids } }).explain('executionStats');
const { executionTimeMillis, totalKeysExamined, totalDocsExamined, nReturned } = ex.executionStats;
console.log(ex.queryPlanner.winningPlan.stage, executionTimeMillis, totalKeysExamined, totalDocsExamined, nReturned);What I look at, in this order:
COLLSCANanywhere in the winning plan means the field is not indexed or the planner could not use the index. For_idthis should never happen.- A
SORTstage you did not expect. Check whether the list crossed 200 values and whether the sort field is in the index. totalKeysExaminedagainstnReturned. About 2 keys per returned document is normal for$inon_id, as the table above shows. If you see 50 or 100 per document, the index is a poor match for the filter.totalDocsExaminedagainstnReturned. These should be close. A big gap means the index narrowed things down badly and MongoDB is filtering after the fetch.executionTimeMillisagainst your own timer. If your measured time is much higher, the cost is in serialising, transferring and decoding, which is where batching, projections and.lean()help.
For the wider picture on indexes, see MongoDB index optimization.
Frequently Asked Questions
Is there a hard limit on the number of items in a MongoDB $in query?
No fixed count. The limit is the size of the query document, 16 MiB of BSON. An ObjectId in an array costs about 20 bytes, so that is roughly 840,000 ids. In my test on server 8.2.4 and driver 7.9.1 a 17.8 MB filter was accepted and the Node driver failed at about 897,000 ids, but do not build on that.
Does MongoDB $in use an index?
Yes, if the field is indexed. It builds one point interval per value and the plan shows IXSCAN, usually under a FETCH. With a sort on top, the plan can also change shape once the list passes 200 values.
What is the optimal batch size for chunking $in queries in Mongoose?
There is no universal number. On my loopback setup, chunks between 100 and 1,000 ids with 4 to 8 queries in flight all finished within about 15% of each other and a quarter to a third faster than one 50,000-id query. Start at 1,000 with 4 concurrent queries and measure against your own network.
Does deduplicating or sorting the id array make $in faster?
Not in my runs. The server already sorts and deduplicates the values. Deduplicating still trims the request size, so it is worth doing for that reason.
Related reading
- MongoDB Index Optimization. Find and remove the indexes that slow your writes before adding new ones.
- Optimize Mongoose Queries with lean(). What
.lean()skips and when that bites. - MongoDB Aggregation Pipeline Performance Tuning. The
$lookuproute from section 5, with stage-order benchmarks.