Skip to content

Menu

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

Try it: mongodb-query-builderFrom the docs, not run by us
{ $group: { _id: "$customerId", spent: { $sum: "$total" }, orders: { $sum: 1 } } }

One output document per customer with total spent and order count

Try it: sql-to-mongodbFrom the docs, not run by us
{ $project: { _id: 0, email: 1, total: 1 } }

Keep only chosen fields; 0 excludes, 1 includes

From the docs, not run by us
{ $addFields: { totalWithTax: { $multiply: ["$total", 1.2] } } }

Add or overwrite fields while keeping everything else ($set is an alias)

From the docs, not run by us
{ $sort: { total: -1 } }

Sort descending by total; -1 descending, 1 ascending

From the docs, not run by us
{ $limit: 10 }

Pass on only the first 10 documents

From the docs, not run by us
{ $skip: 20 }

Drop the first 20 documents, for simple paging

From the docs, not run by us
{ $count: "n" }

Replace the stream with one document holding the number of documents as n

From the docs, not run by us
{ $sortByCount: "$category" }

Group documents by a value and count how many fall in each group

From the docs, not run by us

$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

From the docs, not run by us
{ $unwind: { path: "$items", preserveNullAndEmptyArrays: true } }

Unwind but keep documents whose array is missing or empty

From the docs, not run by us
{ $unwind: { path: "$items", includeArrayIndex: "pos" } }

Unwind and record each element's position in a new field

From the docs, not run by us
{ $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "customer" } }

Left-outer join: add an array of matching customer documents to each order

From the docs, not run by us
{ $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

From the docs, not run by us
{ $unwind: "$customer" }

Turn the one-element array from $lookup back into an embedded object

From the docs, not run by us

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

From the docs, not run by us
{ $push: "$sku" }

Collect every value in the group into an array, duplicates included

From the docs, not run by us
{ $addToSet: "$sku" }

Collect distinct values into an array

From the docs, not run by us
{ $first: "$createdAt" }

Value from the first document to reach each group, so sort before grouping if order matters

From the docs, not run by us
{ $cond: { if: { $gte: ["$total", 100] }, then: "big", else: "small" } }

If/then/else inside a $project, $addFields or $group expression

From the docs, not run by us
{ $ifNull: ["$nickname", "$name"] }

Use a fallback when a field is null or missing

From the docs, not run by us
{ $size: "$items" }

Number of elements in an array field

From the docs, not run by us
{ $filter: { input: "$items", as: "i", cond: { $gt: ["$$i.qty", 0] } } }

Keep only matching array elements without unwinding

From the docs, not run by us
{ $dateToString: { format: "%Y-%m", date: "$createdAt" } }

Format a date, here as year-month for monthly grouping

From the docs, not run by us

$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

From the docs, not run by us
{ $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

From the docs, not run by us
{ $bucketAuto: { groupBy: "$total", buckets: 4 } }

Let MongoDB pick boundaries for four roughly even buckets

From the docs, not run by us

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

From the docs, not run by us
{ $sort: ... }, { $limit: 10 }

The optimizer coalesces these so the sort only keeps the top 10 in memory

From the docs, not run by us
db.orders.aggregate(pipeline, { allowDiskUse: true })

Let stages that need more than 100 megabytes of memory spill to temporary files

From the docs, not run by us
{ $merge: { into: "daily_totals" } }

Write results into a collection; $merge and $out must be the last stage

From the docs, not run by us

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 $lookup or $group before $match.

    Filter first so indexes apply and fewer documents flow through the expensive stages.

  • Assuming results come out of $group in key order.

    $group does not order its output. Add an explicit $sort after it.

  • Losing documents after $unwind and not noticing.

    Plain $unwind drops documents with a missing or empty array. Use preserveNullAndEmptyArrays: true when those rows matter.

  • Using $first in a $group without 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: true so stages can spill to disk.