Aggregation pipeline
Updated 14 October 20262 min read
An aggregation pipeline is MongoDB's way of computing results from documents: an ordered list of stages, where each stage transforms the documents it receives and passes them to the next.
An aggregation pipeline is how you ask MongoDB for anything more than a list of matching documents. Totals, averages, counts per group, joins, time series and reshaped output all come from a pipeline: an array of stages run in order, inside the database, with the output of one stage becoming the input of the next.
Each stage does one job. $match filters documents, much like WHERE in SQL. $group collapses documents that share a key into one result and computes accumulators such as $sum, $avg, $min, $max and $addToSet. $project and $addFields choose, rename or compute fields. $sort orders the stream, and $limit and $skip page through it. $unwind turns one document with an array into one document per element, which is how you aggregate over embedded line items. $lookup joins another collection in the same database, and $facet runs several sub-pipelines over the same input at once.
Order matters, for both correctness and speed. A $match at the start can use an index and reduces how many documents the later stages handle, so it is almost always the first stage. After a $group, the original fields no longer exist: only _id and the accumulators you defined remain, so a later stage that refers to an old field will quietly see nothing. Reading a pipeline means tracking the shape of the documents as they flow from stage to stage.
Pipelines run on the server, so they scale far better than fetching documents and summarising them in application code. They also have limits worth knowing: a stage that needs to hold a lot of data in memory, such as a large $group or an unindexed $sort, can hit MongoDB's memory limit unless disk use is allowed, and joins with $lookup are only fast when the foreign field is indexed.
Pipelines can also write data with $out and $merge, or run JavaScript with $function and $accumulator. Tools that generate pipelines with AI should refuse those stages. wuup only runs pipelines built from an allowlist of read stages, checks every operator before anything reaches your database, and shows you the exact pipeline behind each answer.
The example below computes revenue per month for orders that were not cancelled: filter, group by a formatted month, then sort. It is the same shape as most reporting pipelines you will write.
db.orders.aggregate([
{ $match: { status: { $ne: "cancelled" } } },
{ $group: {
_id: { $dateToString: { format: "%Y-%m", date: "$createdAt" } },
revenue: { $sum: "$total" },
orders: { $sum: 1 }
} },
{ $sort: { _id: 1 } }
])