How does the MongoDB Aggregation Pipeline work?
The Aggregation Pipeline is a multi-stage framework for data transformation and analytics in MongoDB. Documents pass through sequential stages that filter, group, project, sort, and reshape the data stream.
Common stages include: • `$match`: Filters documents (analogous to SQL WHERE). • `$group`: Aggregates values by a specified key (analogous to SQL GROUP BY). • `$project`: Reshapes document fields (analogous to SQL SELECT). • `$unwind`: Deconstructs an array field into individual documents. • `$lookup`: Performs left outer joins to another collection.
db.orders.aggregate([
// Stage 1: Filter to completed orders from 2026
{ $match: { status: "COMPLETED", orderDate: { $gte: new Date("2026-01-01") } } },
// Stage 2: Group by customerId and sum their spending
{
$group: {
_id: "$customerId",
totalSpent: { $sum: "$totalAmount" },
orderCount: { $sum: 1 }
}
},
// Stage 3: Keep only high-value customers
{ $match: { totalSpent: { $gte: 1000 } } },
// Stage 4: Sort descending by total revenue
{ $sort: { totalSpent: -1 } }
]);Each stage takes the output of the preceding stage. Memory is optimized because filtering occurs early in the pipeline via `$match`.
Ready for Indexing Strategies?
Take a quick test to evaluate yourself, or move straight to the next module.