Aggregation Pipeline
The aggregation pipeline is MongoDB's framework for transforming and analyzing data across multiple stages — similar to a Unix pipe, where each stage's output feeds into the next.
1. Pipeline Basics
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: { _id: "$customerId", totalSpent: { $sum: "$amount" } } },
{ $sort: { totalSpent: -1 } }
])
2. Common Pipeline Stages
| Stage | Purpose |
|---|---|
$match | Filter documents (like find()) |
$group | Group documents and compute aggregates |
$project | Reshape documents — include/exclude/compute fields |
$sort | Order documents |
$limit / $skip | Paginate results within the pipeline |
$count | Count matching documents |
3. Grouping and Accumulator Operators
db.sales.aggregate([
{ $group: {
_id: "$region",
totalRevenue: { $sum: "$amount" },
avgOrderValue: { $avg: "$amount" },
maxOrder: { $max: "$amount" },
orderCount: { $count: {} }
}}
])
4. Reshaping with $project
db.employees.aggregate([
{ $project: {
fullName: { $concat: ["$firstName", " ", "$lastName"] },
annualSalary: { $multiply: ["$monthlySalary", 12] },
_id: 0
}}
])
Performance Tip: Place
$match and $sort as early as possible in the pipeline — this lets MongoDB use indexes and reduces the number of documents flowing into later stages.
5. A Complete Example
db.orders.aggregate([
{ $match: { orderDate: { $gte: ISODate("2026-01-01") } } },
{ $group: { _id: "$productCategory", totalSold: { $sum: "$quantity" } } },
{ $sort: { totalSold: -1 } },
{ $limit: 5 }
])
// Returns the top 5 best-selling categories year-to-date
6. Aggregation Pipeline Checklist
- ✅ Chain $match, $group, $sort, $project confidently
- ✅ Use accumulator operators — $sum, $avg, $max, $min
- ✅ Reshape output fields with $project
- ✅ Optimize pipelines by filtering early
Key Takeaway: The aggregation pipeline is MongoDB's answer to SQL's GROUP BY and analytical queries — and it's far more expressive once you're comfortable chaining stages together.
Ready to master MongoDB?
Build real-world MongoDB-powered applications with hands-on projects, mentor-led sessions, and placement support.