Loading lessons...
Aggregation Pipelines
Aggregation Pipelines
Aggregation lets you group, sort, calculate, and analyze data. You do it by building a pipeline of stages - each stage transforms the results of the previous stage.
The aggregate() method
db.posts.aggregate([
// Stage 1: only documents with more than 1 like
{ $match: { likes: { $gt: 1 } } },
// Stage 2: group by category and sum each category's likes
{ $group: { _id: "$category", totalLikes: { $sum: "$likes" } } }
])
How it works
- The pipeline is an array of stages.
- Each stage processes the documents coming from the previous stage.
- Order matters - a
$sortbefore a$limitgives different results than after.
Field references use $
Inside a stage, a field reference starts with $ - like "$category" or "$likes". This tells MongoDB "use the value of this field."
Why aggregations?
- Calculate totals, averages, and counts.
- Group data by categories.
- Join data across collections (
$lookup). - Shape and reshape documents for reporting.
Common stages
| Stage | What it does |
|---|---|
| $match | Filters documents |
| $sort | Orders documents |
| $project | Picks fields to keep |
| $limit | Limits how many documents pass |
| $group | Groups documents by a key |
| $count | Counts documents |
| $addFields | Adds new computed fields |
| $lookup | Joins another collection |
| $out | Writes results to a collection |
TL;DR
- Aggregation = a pipeline of stages passed to
aggregate(). - Each stage transforms the previous stage's output; order matters.
- Field references inside stages use a
$prefix.