Aggregation as a pipeline of stages
coreintermediatedb.collection.aggregate([...]) runs an array of stages in sequence — each stage takes the previous stage's output as its input, transforms or filters it, and passes results to the next. It is MongoDB's tool for grouping, reshaping, and computing across documents, beyond what find() alone can do.
Think of it as
Think of an aggregation pipeline the way you would a Unix pipe chain (grep | sort | uniq) — each stage does one job, and the whole pipeline's behavior comes from composing simple stages in sequence, not from one stage doing everything. find() answers "which documents match" — aggregate() answers "what does the data look like once transformed, grouped, or computed."
What we're doing: Show a short real pipeline and trace what each stage contributes to the final shape.
- 2
- $match filters down to delivered orders only — the first stage narrows the working set before anything more expensive runs.
- 4
- $group reshapes the documents entirely — the output is now one document per customer, not one per order, with a computed total.
Why this works: The pipeline shape (filter, then group, then sort) mirrors how a human would describe the task in words — "delivered orders, totaled per customer, biggest spenders first" — which is what makes aggregation pipelines readable despite doing real analytical work.
Trying to do multi-document aggregation work in application code instead of the pipeline
Wrong
Better
What you see: The application transfers far more data over the network than it needs (every raw order document) and spends CPU time doing work the database is built to do more efficiently.
Why: find() only filters and shapes individual documents — grouping, summing, and other cross-document computation is exactly what the aggregation pipeline exists for, and doing it in the database avoids transferring raw data just to immediately reduce it in application code.
- collection — input documents
- stage 1, stage 2, ... — each transforms the last
- result — transformed output
Remember: aggregate([stage1, stage2, ...]) runs stages in sequence, each transforming the previous stage's output. find() answers "which documents match"; aggregate() answers "what does the data look like transformed, grouped, or computed."
See also: core pipeline stages · pipeline ordering principles

