Skip to content

Aggregation Fundamentals

The Aggregation Pipeline

An ordered list of stages. Documents go in, each stage reshapes them, a result comes out.

IntermediateAbout 6 minutes

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.

  1. 01Documents
  2. 02$match — keep some
  3. 03$group — combine
  4. 04$sort — order
  5. 05$limit — take the top
  6. 06Result
db.orders.aggregate([
  { $match: { status: { $ne: "cancelled" } } },
  { $group: { _id: "$userId", totalSpent: { $sum: "$amount" } } },
  { $sort: { totalSpent: -1 } },
  { $limit: 10 }
])
Total spent per customer, highest first
{ _id: ObjectId("64a1b2c3d4e5f6a7b8c90001"), totalSpent: 18400 }
{ _id: ObjectId("64a1b2c3d4e5f6a7b8c90007"), totalSpent: 15250 }
One document per customer — not the original orders

$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?

Think about it first.

Practice