How to Use Aggregation Pipeline in MongoDB: Syntax and Examples
In MongoDB, the
aggregation pipeline processes data through a sequence of stages, each transforming the documents. Use db.collection.aggregate([stage1, stage2, ...]) to run the pipeline and get aggregated results.Syntax
The aggregation pipeline uses an array of stages, each stage is an object specifying an operation like filtering, grouping, or sorting.
- db.collection.aggregate(): Runs the pipeline on the collection.
- Stages: Objects inside the array, e.g.,
{ $match: {...} }to filter documents. - Stages run in order, passing results from one to the next.
mongodb
db.collection.aggregate([
{ $stage1: { /* operation */ } },
{ $stage2: { /* operation */ } },
// more stages
])Example
This example shows how to find the total sales per product from a sales collection by grouping documents and summing the amounts.
mongodb
db.sales.aggregate([
{ $group: { _id: "$product", totalSales: { $sum: "$amount" } } },
{ $sort: { totalSales: -1 } }
])Output
[
{ "_id": "Laptop", "totalSales": 2500 },
{ "_id": "Phone", "totalSales": 1800 },
{ "_id": "Tablet", "totalSales": 1200 }
]
Common Pitfalls
Common mistakes include:
- Using incorrect stage operators like
$matchinstead of$group. - Not wrapping stages in an array inside
aggregate(). - Forgetting to use the correct field paths with
$prefix. - Expecting aggregation to modify documents in the collection (it only returns results).
mongodb
/* Wrong: missing array brackets */ db.sales.aggregate( { $group: { _id: "$product", totalSales: { $sum: "$amount" } } } ) /* Right: stages inside an array */ db.sales.aggregate([ { $group: { _id: "$product", totalSales: { $sum: "$amount" } } } ])
Quick Reference
| Stage Operator | Purpose |
|---|---|
| $match | Filters documents to pass only those that match conditions |
| $group | Groups documents by a key and applies accumulators like $sum |
| $sort | Sorts documents by specified fields |
| $project | Selects or reshapes fields in documents |
| $limit | Limits the number of documents passed |
| $skip | Skips a number of documents |
| $unwind | Deconstructs arrays to output one document per element |
Key Takeaways
Use db.collection.aggregate() with an array of stages to process data step-by-step.
Each stage performs a specific operation like filtering, grouping, or sorting.
Always wrap stages inside an array when calling aggregate().
Aggregation pipelines return transformed results without changing the original data.
Common stages include $match, $group, $sort, and $project.