What is the aggregation pipeline in MongoDB?
IntermediateConceptMongoDB
Answer
Short answer
The aggregation pipeline processes documents through a series of stages — filter, group, sort, reshape, join — like a Linux pipe. It's MongoDB's way to do reports and analytics: the equivalent of SQL's WHERE, GROUP BY, JOIN and ORDER BY.
Example: revenue per city for shipped orders
db.orders.aggregate([
{ $match: { status: "SHIPPED" } }, // WHERE
{ $lookup: { from: "customers", localField: "customerId",
foreignField: "_id", as: "customer" } }, // JOIN
{ $unwind: "$customer" },
{ $group: { _id: "$customer.address.city",
revenue: { $sum: "$total" }, orders: { $sum: 1 } } }, // GROUP BY
{ $sort: { revenue: -1 } }, // ORDER BY
{ $limit: 5 }
])
Common stages
| Stage | SQL equivalent |
|---|---|
$match |
WHERE |
$group |
GROUP BY |
$sort, $limit, $skip |
ORDER BY, LIMIT, OFFSET |
$project |
SELECT columns |
$lookup |
LEFT JOIN |
$unwind |
Flatten an array |
Performance tip
Put $match first so it can use indexes and reduce documents early.
What to say in the interview
"Aggregation is a staged pipeline — $match, $group, $lookup, $sort, $project — that covers SQL-style filtering, grouping and joins. I put $match early to use indexes and shrink the data before heavy stages."