Question 17 / 50
Must KnowMediumConceptAggregation
What is the aggregation pipeline, and why does stage order matter?
Think about it first.
Short answer
It is a sequence of stages where each stage transforms the stream it receives. Order matters because a later stage only sees the previous stage's output, so filtering early means later stages do less work.
Why?
A $match before $group can use an index and cuts volume immediately; the same $match after $group runs on computed results and cannot use the original index. The planner can move some stages, but not if that would change the result. $sort plus $limit together can become a top-k sort.
Example
db.orders.aggregate([
{ $match: { status: "delivered" } },
{ $group: { _id: "$userId", totalSpent: { $sum: "$amount" } } },
{ $sort: { totalSpent: -1 } },
{ $limit: 10 }
])Interview tip
Saying '$match first, and $sort with $limit so the server can do a top-k sort' covers the two optimisations interviewers look for.
Common mistake
Treating the pipeline as a bag of stages whose order is cosmetic.
How did you do?
Practice
Cheat Sheet