Pipeline Stages
The aggregation pipeline processes documents through a series of stages. Each stage transforms the data and passes it to the next.
Example
// Basic aggregation
db.orders.aggregate([
// Stage 1: Filter
{ $match: { status: "completed" } },
// Stage 2: Group and calculate
{ $group: {
_id: "$category",
totalSales: { $sum: "$amount" },
avgSale: { $avg: "$amount" },
count: { $sum: 1 }
}},
// Stage 3: Sort
{ $sort: { totalSales: -1 } },
// Stage 4: Limit
{ $limit: 5 }
]) Common Pipeline Stages
MongoDB provides many pipeline stages for transforming and analyzing data.
Example
// $project — reshape documents
db.users.aggregate([
{ $project: {
fullName: { $concat: ["$firstName", " ", "$lastName"] },
email: 1,
_id: 0
}}
])
// $unwind — flatten arrays
db.orders.aggregate([
{ $unwind: "$items" },
{ $group: {
_id: "$items.product",
totalQuantity: { $sum: "$items.quantity" }
}}
])
// $lookup — join collections
db.orders.aggregate([
{ $lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "customer"
}}
]) 