Question 38 / 50
You have 50 million orders. How would you efficiently fetch the latest 20 orders for a user?
Short answer
Query { userId } sorted by createdAt descending, limit 20, served by a compound index { userId: 1, createdAt: -1 }. Do not skip() through older pages; for page two use a cursor on createdAt/_id.
Why?
Equality on userId plus sort on createdAt is a textbook ESR index. userId must be the same BSON type you store — ObjectId vs string is a common miss that causes COLLSCAN or empty results. Project only the list fields. If the UI only needs the last 20, do not $lookup every line item's product here.
Example
db.orders.find({ userId: ObjectId("64a1b2c3d4e5f6a7b8c90001") })
.sort({ createdAt: -1 })
.limit(20)
db.orders.createIndex({ userId: 1, createdAt: -1 })Interview tip
Say the index keys out loud, then mention ObjectId type and cursor pagination. That is a complete senior answer.
Common mistake
Indexing only createdAt, then filtering userId — the sort index cannot help the equality on a different leading field.
How did you do?
Practice
Cheat Sheet