1.Aggregation as a pipeline of stages
db.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.
Key features
- db.collection.aggregate([ stage1, stage2, ... ]) — an array of stage objects, in order
- Each stage's output becomes the next stage's input — documents flow through, not processed all-at-once
- A stage can filter documents out, create new ones, or reshape them entirely — not always one-in-one-out
- Most stages can repeat in a pipeline; $out, $merge, and $geoNear cannot appear more than once
- find() answers "which documents match"; aggregate() answers "what does the data look like transformed/grouped/computed"
- collection — input documents
- stage 1, stage 2, ... — each transforms the last
- result — transformed output
Command
db.<collection>.aggregate([ { $stage1: {...} }, { $stage2: {...} }, ... ])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."