MongoDB Aggregation Pipeline Cheat Sheet: Stages, Accumulators, $lookup
Checked against MongoDB MongoDB 9.0 manual (current) on 28 November 2026. Each section links to the official docs it was checked against.
This sheet is for developers who write MongoDB aggregation pipelines and keep forgetting which stage takes which shape. It follows the MongoDB 9.0 manual pages for aggregation, stages, optimization and limits. MongoDB was not available on the machine used to write it, so every row is checked against the docs only and marked untested.
When to use what
Use find with a projection when you only filter and shape documents; reach for aggregate when you need grouping, joins, reshaping arrays or several summaries at once. The operator syntax inside $match is the same query language covered in the MongoDB operators sheet.
Order matters more than anything else. Put $match first, then $sort if you need it, because those two can use indexes only at the start of the pipeline. Project away fields you don't need before a $lookup or $group so less data flows through. The optimizer reorders some stages for you, such as moving a $match ahead of a $sort and merging $sort with a following $limit, but it can't fix a pipeline that groups the whole collection before filtering.
Use $lookup sparingly on hot paths. If you join the same two collections on every request, that is often a sign the data should be embedded; the schema design patterns post covers that trade. To prototype stages without a database, try the MongoDB query builder, and if you think in SQL, the SQL to MongoDB converter gives you a starting pipeline.
A pipeline is an array of stage documents run in order: db.orders.aggregate([ {...}, {...} ]).
{ $match: { status: "paid", total: { $gte: 100 } } }Keep only documents matching a query filter; first in the pipeline so it can use an index
{ $group: { _id: "$customerId", spent: { $sum: "$total" }, orders: { $sum: 1 } } }One output document per customer with total spent and order count
{ $project: { _id: 0, email: 1, total: 1 } }Keep only chosen fields; 0 excludes, 1 includes
{ $addFields: { totalWithTax: { $multiply: ["$total", 1.2] } } }Add or overwrite fields while keeping everything else ($set is an alias)
{ $sort: { total: -1 } }Sort descending by total; -1 descending, 1 ascending
{ $limit: 10 }Pass on only the first 10 documents
{ $skip: 20 }Drop the first 20 documents, for simple paging
{ $count: "n" }Replace the stream with one document holding the number of documents as n
{ $sortByCount: "$category" }Group documents by a value and count how many fall in each group
$unwind options are on https://www.mongodb.com/docs/manual/reference/operator/aggregation/unwind/.
{ $unwind: "$items" }One output document per array element; documents with a null, missing or empty array are dropped
{ $unwind: { path: "$items", preserveNullAndEmptyArrays: true } }Unwind but keep documents whose array is missing or empty
{ $unwind: { path: "$items", includeArrayIndex: "pos" } }Unwind and record each element's position in a new field
{ $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "customer" } }Left-outer join: add an array of matching customer documents to each order
{ $lookup: { from: "orders", let: { cid: "$_id" }, pipeline: [ { $match: { $expr: { $eq: ["$customerId", "$$cid"] } } }, { $limit: 3 } ], as: "recent" } }Join with a sub-pipeline so you can filter, sort or limit the joined documents
{ $unwind: "$customer" }Turn the one-element array from $lookup back into an embedded object
Expression operators are listed at https://www.mongodb.com/docs/manual/reference/mql/expressions/. $group does not order its output, so add $sort after it if order matters.
{ $avg: "$total" }, { $min: "$total" }, { $max: "$total" }Average, lowest and highest value per group
{ $push: "$sku" }Collect every value in the group into an array, duplicates included
{ $addToSet: "$sku" }Collect distinct values into an array
{ $first: "$createdAt" }Value from the first document to reach each group, so sort before grouping if order matters
{ $cond: { if: { $gte: ["$total", 100] }, then: "big", else: "small" } }If/then/else inside a $project, $addFields or $group expression
{ $ifNull: ["$nickname", "$name"] }Use a fallback when a field is null or missing
{ $size: "$items" }Number of elements in an array field
{ $filter: { input: "$items", as: "i", cond: { $gt: ["$$i.qty", 0] } } }Keep only matching array elements without unwinding
{ $dateToString: { format: "%Y-%m", date: "$createdAt" } }Format a date, here as year-month for monthly grouping
$bucket details: https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket/. Each bucket includes its lower boundary and excludes its upper one.
{ $facet: { byStatus: [ { $sortByCount: "$status" } ], top: [ { $sort: { total: -1 } }, { $limit: 5 } ] } }Run several sub-pipelines over the same input and return them as fields of one document
{ $bucket: { groupBy: "$total", boundaries: [0, 100, 500], default: "Other", output: { n: { $sum: 1 } } } }Count documents in price bands 0-99 and 100-499, with everything else in Other
{ $bucketAuto: { groupBy: "$total", buckets: 4 } }Let MongoDB pick boundaries for four roughly even buckets
Memory and size limits are on https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits/.
[ { $match: ... }, { $sort: ... }, ... ]Put $match and $sort at the start so the query planner can use an index
{ $sort: ... }, { $limit: 10 }The optimizer coalesces these so the sort only keeps the top 10 in memory
db.orders.aggregate(pipeline, { allowDiskUse: true })Let stages that need more than 100 megabytes of memory spill to temporary files
{ $merge: { into: "daily_totals" } }Write results into a collection; $merge and $out must be the last stage
Worked example: Top customers by month, with their names
Goal: for paid orders since November, total spend per customer, top five, with the customer's name attached.
db.orders.aggregate([
{ $match: { status: "paid", createdAt: { $gte: ISODate("2026-11-01") } } },
{ $group: { _id: "$customerId", spent: { $sum: "$total" }, orders: { $sum: 1 } } },
{ $sort: { spent: -1 } },
{ $limit: 5 },
{ $lookup: { from: "customers", localField: "_id", foreignField: "_id", as: "customer" } },
{ $unwind: "$customer" },
{ $project: { _id: 0, name: "$customer.name", spent: 1, orders: 1 } }
])
I couldn't run this here, so here is what to check when you do. Each output document should have name, spent and orders and nothing else, sorted by spent descending. If you get fewer than five results even though you have more customers, an order's customerId probably has no matching customer: plain $unwind drops documents whose customer array is empty. Add preserveNullAndEmptyArrays: true to see them. The order of stages is deliberate. $match comes first so an index on { status: 1, createdAt: 1 } can be used, and the $lookup runs after $limit, so it does five lookups instead of one per customer. In the explain output for the pipeline, look for an IXSCAN in the first stage rather than a COLLSCAN.
Common mistakes
Writing
$group: { _id: "customerId" }without the dollar sign.Field paths in expressions need
$:"$customerId". Without it every document lands in one group keyed by the literal string.Putting
$lookupor$groupbefore$match.Filter first so indexes apply and fewer documents flow through the expensive stages.
Assuming results come out of
$groupin key order.$groupdoes not order its output. Add an explicit$sortafter it.Losing documents after
$unwindand not noticing.Plain
$unwinddrops documents with a missing or empty array. UsepreserveNullAndEmptyArrays: truewhen those rows matter.Using
$firstin a$groupwithout sorting beforehand.Without a
$sort, 'first' is whatever order documents arrive in. Sort before the group.Hitting the memory limit on a big sort or group.
Filter and project earlier, add an index for the sort, or pass
allowDiskUse: trueso stages can spill to disk.
Related cheat sheets
Sources
- https://www.mongodb.com/docs/manual/aggregation/
- https://www.mongodb.com/docs/manual/reference/mql/aggregation-stages/
- https://www.mongodb.com/docs/manual/core/aggregation-pipeline-optimization/
- https://www.mongodb.com/docs/manual/core/aggregation-pipeline-limits/
- https://www.mongodb.com/docs/manual/reference/operator/aggregation/lookup/
- https://www.mongodb.com/docs/manual/reference/operator/aggregation/unwind/
- https://www.mongodb.com/docs/manual/reference/operator/aggregation/group/
- https://www.mongodb.com/docs/manual/reference/operator/aggregation/facet/
- https://www.mongodb.com/docs/manual/reference/operator/aggregation/bucket/
- https://www.mongodb.com/docs/manual/reference/mql/expressions/
How we research: where our facts come from, how often we re-check them, and why no one can pay for a review or a verdict.