Aggregation Fundamentals
The Aggregation Pipeline
An ordered list of stages. Documents go in, each stage reshapes them, a result comes out.
A pipeline is an ordered list of stages. Each stage receives documents, transforms them, and passes the result on. Order is part of the meaning.
- 01Documents
- 02$match — keep some
- 03$group — combine
- 04$sort — order
- 05$limit — take the top
- 06Result
db.orders.aggregate([
{ $match: { status: { $ne: "cancelled" } } },
{ $group: { _id: "$userId", totalSpent: { $sum: "$amount" } } },
{ $sort: { totalSpent: -1 } },
{ $limit: 10 }
]){ _id: ObjectId("64a1b2c3d4e5f6a7b8c90001"), totalSpent: 18400 }
{ _id: ObjectId("64a1b2c3d4e5f6a7b8c90007"), totalSpent: 15250 }$match first → fewer documents into $group. $sort then $limit after grouping → you rank customers, not raw orders. $match after $group cannot see status unless you accumulated it. The planner may reorder some stages; it will not reorder anything that would change the result. Write the story you mean.
Interview question
What is the aggregation pipeline, and why does stage order matter?
A sequence of stages; each sees only the previous stage's output. Filter early so later stages do less work. $match before $group can use an index; the same $match after $group runs on computed results and cannot see original fields you did not accumulate.
Practice