Question 39 / 50
ImportantMediumDebuggingPerformance
Page 1 of this API is fast. Page 5000 is not. Why, and what would you do instead?
db.orders.find({ userId: userId })
.sort({ createdAt: -1 })
.skip(page * 20)
.limit(20)Think about it first.
Short answer
skip(n) still walks n index keys (or documents). Cost grows with page number. Use cursor pagination: the next page starts after the last { createdAt, _id } you returned.
Why?
Offset pagination is fine for small admin lists. It is the wrong default for a 50 million order history. A unique sort key — typically createdAt plus _id to break ties — lets the next query use a range: createdAt < last, or the compound equivalent.
Example
db.orders.find({
userId: userId,
_id: { $lt: lastId }
}).sort({ _id: -1 }).limit(20)Interview tip
Mention that skip is not 'free just because there is an index'. The index still has to be walked.
Common mistake
Raising the limit or adding another index on page instead of changing the pagination model.
How did you do?