All academies
Roadmap
LEVEL 5 · AGGREGATION FRAMEWORK

The Pipeline Model

12 min read

Aggregation processes documents through a pipeline of stages. Each stage receives documents, transforms them, and passes results to the next stage — like Unix pipes for your data.

Top 5 customers by spend
db.orders.aggregate([
  { $match: { status: "delivered" } },   // filter first
  { $group: {
      _id: "$userId",
      totalSpent: { $sum: "$total" },
      orders: { $sum: 1 }
  }},
  { $sort: { totalSpent: -1 } },
  { $limit: 5 }
])

$match and $sort

$match uses the same syntax as find(). Put it first whenever possible so later stages process fewer documents (and so it can use indexes).

$group and accumulators

$group collects documents by the _id expression and computes accumulators: $sum, $avg, $min, $max, $push, $addToSet, $first, $last. Use { $sum: 1 } to count.

mongosh
db.products.aggregate([
  { $group: {
      _id: "$category",
      avgPrice: { $avg: "$price" },
      count: { $sum: 1 }
  }}
])

Field references

Strings starting with $ reference fields: "$price" means *the value of the price field*. _id: null groups everything into one bucket.

Try it yourself

db.products.aggregate([{ $group: { _id: "$category", avgPrice: { $avg: "$price" }, count: { $sum: 1 } } }])
Run in Shell

Check your understanding

Q1.

Why should $match come as early as possible in a pipeline?

Q2.

What does _id: null do in a $group stage?

code
db.orders.aggregate([{ $group: { _id: null, total: { $sum: "$total" } } }])
Q3.

How do you count documents per group?