Skip to content

Lesson 5 of 9 · 27m

Aggregation Pipelines in Practice

Build aggregation pipelines that filter early, use indexes where possible, avoid accidental memory bombs, and produce evidence rather than mystery.

Aggregation pipelines are MongoDB's sharpest tool and one of its easiest self-inflicted wounds. A well-ordered pipeline can turn a slow reporting endpoint into an index-driven lookup. A badly ordered one can copy half a collection into memory, sort it, group it, and then explain itself with a timeout. Pipelines are programs. Treat them with the same skepticism as application code.

Filter first, project early, sort with intent

MongoDB can use indexes in early $match and $sort stages. Put selective filters at the front:

db.orders.aggregate([
  { $match: {
      customerId: ObjectId("665f1c22bfd34cf7b2785c80"),
      createdAt: { $gte: ISODate("2026-10-01T00:00:00Z") }
  } },
  { $sort: { createdAt: -1 } },
  { $limit: 100 },
  { $project: {
      customerId: 1, status: 1, createdAt: 1,
      total: { $ifNull: ["$totals.subtotal", 0] }
  } }
])

Do not $unwind before filtering if the filter can shrink the working set first. Every stage has a cost model even if the syntax feels declarative.

$group is where memory goes to die

Grouping builds state. Grouping millions of rows by a high-cardinality key is not a reporting shortcut; it is a resource plan:

db.orders.aggregate([
  { $match: { createdAt: { $gte: ISODate("2026-10-01T00:00:00Z") } } },
  { $group: {
      _id: { customerId: "$customerId", day: { $dateTrunc: { date: "$createdAt", unit: "day" } } },
      revenue: { $sum: "$totals.subtotal" },
      orderCount: { $sum: 1 }
  } },
  { $sort: { "_id.day": -1, revenue: -1 } }
])

MongoDB spills some blocking operations to disk when allowDiskUse applies, but disk spill is not a performance strategy. Pre-aggregate hot metrics into summary collections when the same rollup is requested repeatedly.

$facet multiplies work, not wisdom

$facet runs multiple pipelines over the same input. It is useful for search result metadata, but remember that expensive branches still execute:

[
  { $match: { tenantId, status: { $in: ["paid", "packed"] } } },
  { $facet: {
      results: [{ $sort: { createdAt: -1 } }, { $limit: 20 }],
      statusCounts: [{ $group: { _id: "$status", count: { $sum: 1 } } }]
  } }
]

This can be elegant. It can also hide five expensive aggregations behind one innocent endpoint. Measure each branch.

Beware type and null semantics

Aggregation expressions are precise about types. $sum ignores non-numeric values in some contexts, comparisons follow BSON type ordering, and missing fields differ from explicit null. A pipeline that looks correct on clean test data may silently produce different results when legacy documents contain strings or absent fields.

Debug with explain and stage isolation

Use explain for pipelines:

db.orders.explain("executionStats").aggregate(pipeline)

Then bisect the pipeline. Run the first two stages, then three, then four. Record documents in and out of each stage. Most pipeline incidents become obvious when you see where cardinality explodes.

Field notes

  • $lookup can be appropriate for reporting, but inspect whether the foreign collection side is indexed.
  • $unwind turns one document into many; always ask what the cardinality multiplier is.
  • Date truncation and bucket operators are usually clearer than hand-built date-part objects.
  • If a dashboard runs the same heavy pipeline every few seconds, the answer is often a materialized rollup, not a bigger server.

Was this lesson helpful?

Sign in to rate