MongoDB Aggregation Pipeline Explained
Advertisement
Ad
What is the Aggregation Pipeline?
Aggregation processes documents through a series of stages — filtering, grouping, transforming — to compute results like totals and averages. Think of it as MongoDB's version of SQL GROUP BY but far more powerful.
A Simple Pipeline
db.orders.aggregate([
{ $match: { status: "completed" } }, // filter
{ $group: {
_id: "$customerId",
total: { $sum: "$amount" } // sum per customer
}},
{ $sort: { total: -1 } } // highest first
]);
Common Stages
| Stage | Does |
|---|---|
| $match | Filter documents |
| $group | Group & aggregate |
| $sort | Order results |
| $project | Reshape fields |
| $lookup | Join collections |
Joining with $lookup
db.orders.aggregate([
{ $lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "user"
}}
]);
FAQs
When use aggregation vs find?
Use find for simple queries; aggregation for grouping, joins, and computed results. More in our MongoDB guides.
Is aggregation fast?
Yes, especially with indexes on $match fields placed early.
