If you use MongoDB only with find(), you are using maybe ten percent of the database. The moment you need “total revenue per category this quarter” or “top 10 customers by order value with their latest order,” find() runs out of road — and developers start pulling thousands of documents into application code to crunch them by hand. That is slow, memory-hungry, and completely unnecessary.
The aggregation pipeline is MongoDB's answer: a chain of stages where documents flow in one end, get filtered, reshaped, grouped, and joined, and come out the other end as exactly the answer you asked for. If you know SQL, think of it as WHERE + GROUP BY + JOIN composed as a readable pipeline instead of one nested statement. This guide builds your intuition stage by stage, with copy-paste examples you can run in mongosh today.
1. Pipelines, Not Queries: The Mental Model
An aggregation pipeline is an array of stage objects passed to db.collection.aggregate(). Each stage transforms the stream of documents and hands the result to the next stage. Order matters: filter early so later stages do less work.
db.orders.aggregate([
{ $match: { status: "paid" } }, // stage 1: keep paid orders
{ $project: { total: 1, customerId: 1 } }, // stage 2: keep 2 fields
{ $limit: 5 } // stage 3: first 5 docs
]);
Three stages, one round trip to the database. The application never sees the orders you filtered out — they were discarded inside MongoDB. Keep this picture in mind: documents flow down, each stage narrows or enriches the stream.
2. $match and $project: Filter Early, Shape Lean
$match is the pipeline's WHERE clause, and it should almost always be your first stage. MongoDB can use indexes in $match, which means filtering a million documents down to a thousand before doing anything expensive. $project then trims each document to the fields you actually need — less data moving between stages, faster everything.
db.orders.aggregate([
{ $match: { createdAt: { $gte: new Date("2026-01-01") }, status: "paid" } },
{ $project: {
_id: 0,
orderId: "$orderNumber", // rename a field
total: 1,
itemCount: { $size: "$items" }, // computed field: array length
isBigOrder: { $gte: ["$total", 500] } // boolean expression
}}
]);
Notice the $ prefix: inside expressions, "$total" means “the value of the total field in the current document.” This expression language — $size, $gte, $concat, $dateToString and dozens more operators — is what makes stages composable without leaving the database.
3. $group: Your New GROUP BY
$group collapses documents by a key you choose (_id in the stage defines the grouping key) and computes accumulators over each group: $sum, $avg, $min, $max, $push, $first, $last. The classic “revenue per category” report becomes one stage:
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $unwind: "$items" }, // one doc per line item
{ $group: {
_id: "$items.category", // group key
revenue: { $sum: "$items.price" },
unitsSold: { $sum: "$items.qty" },
avgPrice: { $avg: "$items.price" },
orders: { $addToSet: "$_id" } // unique order ids
}},
{ $project: { category: "$_id", revenue: 1, unitsSold: 1, avgPrice: { $round: ["$avgPrice", 2] }, _id: 0 } },
{ $sort: { revenue: -1 } }
]);
Two things to steal from this pattern. First, $unwind explodes an array field so each element becomes its own document — the standard trick for line-item math. Second, $addToSet collects unique values, handy for counting distinct orders after an unwind. Grouping by a date part works the same way: _id: { $dateToString: { format: "%Y-%m", date: "$createdAt" } } gives you monthly buckets.
4. $sort, $limit, $skip: Top-N Done Right
Leaderboards and “top 10” lists are a $sort + $limit pair, and order matters for performance: $sort before $limit lets MongoDB use a top-k sort that never materializes the full sorted set. Put $limit as early as the logic allows.
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $group: { _id: "$customerId", totalSpent: { $sum: "$total" }, orderCount: { $sum: 1 } } },
{ $sort: { totalSpent: -1 } }, // biggest spenders first
{ $limit: 10 }, // keep only 10
{ $project: { customerId: "$_id", totalSpent: 1, orderCount: 1, _id: 0 } }
]);
Avoid $skip for deep pagination — skipping 100,000 documents still reads 100,000 documents. For “load more” UIs, prefer keyset pagination: remember the last totalSpent seen and $match for values below it.
5. $lookup: Joins Without the Fear
MongoDB is a document database, but real apps still need joins — orders referencing customers, posts referencing authors. $lookup performs a left outer join against another collection inside the pipeline, attaching matched documents as an array field you can then unwind or project.
db.orders.aggregate([
{ $match: { status: "paid" } },
{ $lookup: {
from: "customers", // target collection
localField: "customerId", // field in orders
foreignField: "_id", // field in customers
as: "customer" // output array field
}},
{ $unwind: "$customer" }, // array of 1 -> object
{ $project: { _id: 0, orderNumber: 1, total: 1,
customerName: "$customer.name", customerCity: "$customer.city" } }
]);
Two practical rules: keep the $lookup after your $match so you only join the documents you need, and make sure the foreign field is indexed — an unindexed $lookup on a large collection is the most common aggregation performance disaster.
6. $unwind and $facet: Arrays and Multi-Result Dashboards
We met $unwind in section 3. Its partner for analytics is $facet, which runs multiple sub-pipelines over the same input documents in a single pass and returns each result under its own key. One query can power an entire dashboard:
db.orders.aggregate([
{ $match: { createdAt: { $gte: new Date("2026-10-01") } } },
{ $facet: {
revenueByDay: [
{ $group: { _id: { $dateToString: { format: "%Y-%m-%d", date: "$createdAt" } },
revenue: { $sum: "$total" } } },
{ $sort: { _id: 1 } }
],
byStatus: [
{ $group: { _id: "$status", count: { $sum: 1 } } }
],
topProducts: [
{ $unwind: "$items" },
{ $group: { _id: "$items.sku", units: { $sum: "$items.qty" } } },
{ $sort: { units: -1 } },
{ $limit: 5 }
]
}}
]);
The result is a single document with revenueByDay, byStatus, and topProducts arrays — three database round trips collapsed into one. For admin panels and reporting pages, $facet is the highest-leverage stage most developers never use.
7. Performance: Indexes, Stage Order, and Memory
Aggregations are fast when you respect three rules. Filter first: $match and $limit as early as possible shrink everything downstream. Index the match: run db.orders.explain("executionStats").aggregate([...]) and check that your $match uses an IXSCAN, not a COLLSCAN. Watch the 100MB limit: individual stages spill past 100MB of RAM unless you pass { allowDiskUse: true } — fine for nightly reports, a red flag for user-facing queries that should be narrowed instead.
Frequently Asked Questions (FAQ)
Q: When should I use aggregation instead of find()?
Use find() for fetching documents. Reach for aggregate() when the answer requires combining, grouping, or reshaping documents — counts, sums, joins, and dashboards. If you find yourself looping over find() results in application code to compute totals, that loop belongs in a pipeline.
Q: Is $lookup slow? Should I embed instead of referencing?
$lookup on an indexed foreign key is fast — comparable to a SQL join. Embed data you always read together (order line items inside the order), and reference + $lookup data that changes independently or is shared (customers, products). The right schema makes most joins unnecessary; $lookup covers the rest.
Q: Can I save an aggregation result back to a collection?
Yes — end the pipeline with $merge (upsert into an existing collection, great for materialized dashboards) or $out (replace a collection entirely, great for nightly rebuilds). Both must be the final stage.
Conclusion
The aggregation pipeline rewards one habit: push work into the database. Filter with $match before anything else, group with $group instead of application loops, join with $lookup on indexed keys, and fan out with $facet when one query should answer three questions. Learn these five stages and you will delete more application code than any new framework could.
💡 Engineering Key Takeaway
Read every pipeline top-to-bottom as a story: “take paid orders, explode line items, group by category, sort by revenue.” If you cannot narrate it in one sentence, a stage is in the wrong place — usually the $match that should have been first.