Transform and analyze data with $match, $group, $sort, $lookup, and $project stages.
The aggregation pipeline is like a series of Unix pipes. Each stage transforms the documents and passes results to the next stage.
db.orders.aggregate([
// Stage 1: filter documents
{ $match: { status: 'completed' } },
// Stage 2: group and calculate
{ $group: {
_id: '$category',
totalRevenue: { $sum: '$amount' },
orderCount: { $count: {} },
avgOrder: { $avg: '$amount' }
}},
// Stage 3: sort results
{ $sort: { totalRevenue: -1 } },
// Stage 4: limit
{ $limit: 10 },
// Stage 5: reshape output
{ $project: {
_id: 0,
category: '$_id',
totalRevenue: 1,
orderCount: 1,
avgOrder: { $round: ['$avgOrder', 2] }
}}
])// Join users to their orders
db.orders.aggregate([
{ $lookup: {
from: 'users',
localField: 'userId',
foreignField: '_id',
as: 'user'
}},
{ $unwind: '$user' }, // flatten the user array
{ $project: {
orderId: '$_id',
amount: 1,
userName: '$user.name',
userEmail: '$user.email'
}}
])$match → $group → $sort → $project.$group with $sum, $avg, $count, $min, $max for analytics.$lookup joins collections. Follow with $unwind to flatten the joined array.$match first so subsequent stages process fewer documents.