Lesson 7 of 9 · 25m
Aggregation Pipeline Craft
Pipelines are query programs — stage order, memory limits, `$lookup`, `$facet`, and the difference between analytics and application logic.
The aggregation pipeline is where MongoDB stops being merely a document store and becomes a data-processing engine. It is also where good intentions produce 12-stage monsters that allocate gigabytes and time out in production. Treat a pipeline as a program with a cost model, not as a fluent API toy.
Put reduction early
db.orders.aggregate([
{ $match: { tenantId: tenant, createdAt: { $gte: monthStart } } },
{ $project: { status: 1, total: 1, createdAt: 1 } },
{ $group: { _id: "$status", orders: { $sum: 1 }, revenue: { $sum: "$total" }, firstAt: { $min: "$createdAt" } } },
{ $sort: { revenue: -1 } }
])The first $match can use indexes. $project early reduces document size through later stages. $group is blocking: it generally must consume all input before emitting final groups. A careless pipeline that groups the entire collection and filters afterward has inverted the cost model.
Blocking stages are the memory boundary
$group and $sort can consume large amounts of memory. MongoDB enforces a per-stage memory limit (historically 100 MB) unless allowDiskUse(true) permits spilling to temporary files:
db.events.aggregate(pipeline, { allowDiskUse: true })That flag is not permission to be sloppy. Disk-spilled aggregation is often the correct tool for a nightly analytics job and the wrong tool for an interactive endpoint.
$lookup is a join with a brake pedal
{ $lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customer"
} },
{ $unwind: "$customer" }Useful, yes. Free, no. If every request performs several lookups, reconsider the document model or maintain a purpose-built read collection. On hot paths, embedding or application-level batch fetching is often more predictable.
$facet runs multiple pipelines over one input
$facet is excellent for dashboards: totals by status plus top customers plus daily counts from the same matched subset. But each facet consumes memory, and the stage can duplicate expensive downstream processing. Explain and measure rather than assuming one pass means cheap.
Pipeline-style updates are underrated
Aggregation syntax is not only for reads:
db.inventory.updateMany({ reorder: true }, [{ $set: { targetStock: { $max: ["$minStock", { $multiply: ["$weeklyVelocity", 2] }] } } }])This computes new values from old document values server-side. It is often safer and faster than read-transform-write loops.
Field notes
- Only leading
$matchand$sortstages can exploit indexes before reshaping stages change the data. $unwindon large arrays multiplies documents. A 200-element array becomes 200 pipeline rows.- Use
explain()on aggregations too; people forget because the syntax feels procedural. - If a pipeline is business-critical reporting, materialize results into a collection on a schedule rather than recomputing under user traffic.
Was this lesson helpful?