The MongoDB aggregation pipeline is the engine behind every non-trivial query — reports, dashboards, denormalized projections, joins via $lookup. It is also where most MongoDB performance disasters originate, because pipelines are easy to write and very hard to read when they go wrong. This article covers stage ordering, index usage, the rules the planner uses to rewrite your pipeline, and how to read explain output that does not lie to you.
How to verify
Use explain at executionStats verbosity to see what the server actually did:
mongosh --host primary.example.internal:27017
use shop
db.orders.aggregate([
{ $match: { status: "paid", placedAt: { $gte: ISODate("2026-05-01") } } },
{ $group: { _id: "$customerId", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } },
{ $limit: 20 }
], { explain: true })
db.orders.getIndexes()
Look for IXSCAN (index scan) in the first stage, not COLLSCAN (collection scan). Look for totalDocsExamined close to nReturned — large ratios mean the pipeline is reading documents that fail filters later. executionTimeMillis is the wall clock.
What’s happening
A pipeline is an ordered list of stages. Each stage receives documents from the previous stage, transforms or filters them, and emits documents to the next stage. The first stage runs against the collection; subsequent stages operate on the in-memory stream. The planner is allowed to rewrite the pipeline — moving $match ahead of $project, fusing adjacent $limit and $sort into a top-K, pushing $lookup foreign-key match into the foreign collection’s index — but it cannot rewrite things that change semantics.
The single most important property of a pipeline is whether the first stage can use an index. $match and $sort at the top of a pipeline can both use indexes; once the pipeline emits anything that is not a verbatim document from the collection (after $group, $project of a computed field, $unwind), the index is no longer available to later stages. This is why “filter first, transform second” is not a stylistic preference — it determines whether the query runs in milliseconds or seconds.
Memory limits matter. Each stage is bounded to 100 MiB of in-memory state by default. Stages that buffer entire result sets ($sort without a supporting index, $group with high-cardinality keys, $bucketAuto) will fail when they exceed the limit unless you pass allowDiskUse: true. Disk use works but is roughly an order of magnitude slower than memory; a pipeline that constantly spills is a pipeline that needs a different design.
The procedure
-
Put the most selective
$matchfirst. If you can drop 99% of documents up front, every later stage is 100× faster.db.orders.aggregate([ { $match: { tenantId: 42, placedAt: { $gte: ISODate("2026-05-01") } } }, { $project: { customerId: 1, amount: 1 } } ]) -
Build a compound index that supports the leading
$matchand$sort. The ESR rule (Equality, Sort, Range) gives the right field ordering — equality fields first, sort fields next, range fields last.db.orders.createIndex({ tenantId: 1, placedAt: -1, status: 1 }) -
Replace late
$sort+$limitwith the top-K optimization. Adjacent$sortand$limitare fused by the planner into a heap-based top-K — bounded memory regardless of input size.{ $sort: { total: -1 } }, { $limit: 20 } -
Use
$lookupwithlocalField/foreignFieldform for indexed joins. The pipeline form is more flexible but loses the implicit index use unless the inner pipeline starts with an indexed$match.{ $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "customer" } }, { $unwind: "$customer" } -
Prefer
$groupwith a small key cardinality over$bucket/$bucketAutowhen you can. Grouping ten million documents into 50 buckets is fast; grouping into 10 million buckets is not. -
Profile the slow pipelines. Enable the database profiler at level 1 (slow operations only) with a threshold tuned to your tolerance.
db.setProfilingLevel(1, { slowms: 200 }) db.system.profile.find({ op: "command", "command.aggregate": { $exists: true } }).sort({ ts: -1 }).limit(20)
Operational notes
allowDiskUse: trueis a band-aid, not a fix. A pipeline that requires disk use under normal load needs a smaller working set — narrow the$match, add an index, or denormalize the answer in a materialized collection.$outand$mergeare destructive.$outreplaces the target collection atomically;$mergeupserts on a key. Run with read-only credentials when testing.- Pipeline length is not the metric. A 20-stage pipeline with an indexed first
$matchoutperforms a 3-stage pipeline that does aCOLLSCAN. Stage count is irrelevant; stage cost is everything. - The planner does not always pick the best index. Add a
hintto force a specific index when you have evidence the planner is wrong —db.coll.aggregate([…], { hint: "ix_tenantId_placedAt" }). - Sharded pipelines run partly on each shard, partly on the merging mongos. Stages with
$mergeIndexes: truesemantics (lookup-able) run on shards; stages that need cross-shard data ($groupwithout a shard-key prefix,$lookupforeign collection) run on the merging mongos and can become a bottleneck.
Stack Harbor designs MongoDB aggregations against the real query mix our clients run — reports that ran for ten minutes get re-shaped into pipelines that run in single-digit seconds, often without a schema change. We instrument the slow-query profile, attach pipeline reviews to incident postmortems, and maintain the index set that supports the most expensive queries. See /en/knowledge-base/ for related MongoDB articles on sharding and change streams.