Query Performance
Large Collection Problems
What changes when a collection no longer fits in memory, including pagination.
On a laptop dataset, everything is in RAM and COLLSCAN looks fine. At millions of orders the working set — documents and indexes you actually touch — must fit in the WiredTiger cache or every read becomes disk. That is when skip, unbounded find, and 'just $lookup users' fall over together.
- Pagination.
skip(n)walks n keys every time — Module 5. Cursor +_idtiebreaker, with an index that matches the sort. - Counts.
countDocumentson a fat filter is another heavy query.estimatedDocumentCountis metadata. APIs that need 'page 4 of 80,221' pay for it; feeds should not. - Materialising.
.toArray()on an unbounded cursor in Node pulls the collection into the process. Stream, orlimit. - Indexes bigger than RAM. A 20-index
orderscollection that does not fit is slower than fewer indexes that do.$indexStats, drop. - Joins.
$lookupper document against a huge foreign collection needs an index on the foreign field and a small left side ($match/$limitfirst).
Sharding is how you split a collection you cannot host on one replica set — Production, not a first fix. First fixes: smaller working set, cursor pagination, fewer indexes, no collection scan on the hot path. Prove each with explain on production-shaped data, not on 42 users.
Interview question
What breaks when a MongoDB collection gets large?
If the working set no longer fits in RAM, index and document reads hit disk. skip() cost grows with offset. Unbounded find().toArray() blows up the app. countDocuments on a list endpoint becomes a second scan. $lookup without a small left side and a foreign index walks too much. Fix: cursor pagination, fewer hot indexes, project/limit, measure with explain on production-sized data — not sharding first.