Index keys used in $match and $sort, allowDiskUse for large sorts, and avoid massive $lookup without filters.
Explain aggregation
db.orders.aggregate([
{ $match: { status: 'open' } },
{ $sort: { createdAt: -1 } },
{ $limit: 20 }
]).explain('executionStats')Practice: Run aggregation pipelines in mongosh.
Tips
- Match early; project only needed fields before heavy stages
- Index { status: 1, createdAt: -1 } if that query is hot
- Pre-filter $lookup sub-pipeline
- Consider $merge during off-peak for large materializations
Important interview questions and answers
- Q: allowDiskUse?
A: Lets large sorts spill to disk—slower but prevents memory cap errors. - Q: $lookup cardinality?
A: Joining huge collections without $match explodes RAM.
Self-check
- Two ways to speed $match stage.
- Risk of late $project?
Tip: explain('executionStats') on pipelines reveals slow stages.
Interview prep
- allowDiskUse?
- Spills large sorts to disk when memory cap hit.
- $lookup filter?
- Pre-filter sub-pipeline to limit join size.