Advanced
Aggregation Pipeline
Transform and analyze data using MongoDB's powerful aggregation framework.
The Aggregation Pipeline
The aggregation pipeline processes documents through a series of stages. Each stage transforms the documents and passes results to the next stage.
Common Pipeline Stages
$match— filter documents (like WHERE)$group— group documents and compute aggregates$project— include/exclude/reshape fields (like SELECT)$sort— sort documents$limit— limit number of documents$skip— skip documents$lookup— join with another collection$unwind— deconstruct an array field$addFields— add computed fields$count— count documents
Example
javascript
// Sales analytics aggregation
const result = await db.collection('orders').aggregate([
// Stage 1: Filter
{ $match: {
status: 'completed',
createdAt: { $gte: new Date('2024-01-01') }
}},
// Stage 2: Group by category and compute totals
{ $group: {
_id: '$category',
totalRevenue: { $sum: '$total' },
orderCount: { $count: {} },
avgOrderValue: { $avg: '$total' },
maxOrder: { $max: '$total' }
}},
// Stage 3: Add computed field
{ $addFields: {
revenuePerOrder: { $divide: ['$totalRevenue', '$orderCount'] }
}},
// Stage 4: Sort by revenue descending
{ $sort: { totalRevenue: -1 } },
// Stage 5: Take top 5
{ $limit: 5 },
// Stage 6: Reshape output
{ $project: {
category: '$_id',
totalRevenue: { $round: ['$totalRevenue', 2] },
orderCount: 1,
avgOrderValue: { $round: ['$avgOrderValue', 2] },
_id: 0
}}
]).toArray();
// $lookup - join with users collection
const ordersWithUsers = await db.collection('orders').aggregate([
{ $lookup: {
from: 'users',
localField: 'userId',
foreignField: '_id',
as: 'user'
}},
{ $unwind: '$user' },
{ $project: {
orderTotal: '$total',
userName: '$user.name',
userEmail: '$user.email'
}}
]).toArray();Want to run this code interactively?
Try in Compiler