Question 46 / 50
This query became slow after orders reached 50 million documents. What would you investigate?
db.orders.find({
userId: "64a1b2c3d4e5f6a7b8c90001"
}).sort({
createdAt: -1
}).limit(20)Short answer
Check explain: you want IXSCAN on a compound index { userId: 1, createdAt: -1 }. Then check types: if userId is stored as ObjectId, this string filter will not use the index usefully and may scan. Also confirm you are not skip-paginating, and that the sort is in the index (ESR).
Why?
The query shape is right for a user history. The usual production bugs are: string vs ObjectId, an index on createdAt only, no index at all (COLLSCAN), or skip for deep pages. Selectivity is excellent once userId matches the indexed type — one user's 20 rows out of 50 million should be cheap.
Example
db.orders.find({ userId: ObjectId("64a1b2c3d4e5f6a7b8c90001") })
.sort({ createdAt: -1 })
.limit(20)Interview tip
Walk explain, type, compound index, pagination — in that order. That checklist is the answer.
Common mistake
Only saying 'add an index' without specifying the keys or the ObjectId trap.
How did you do?
Cheat Sheet