Introduction to the Aggregation Pipeline
11 min read
The Aggregation Pipeline
The aggregation pipeline is MongoDB's answer to SQL GROUP BY, JOIN, and computed columns. Documents flow through a series of stages — each stage transforms the stream and passes it to the next.
Common stages: $match (filter), $group (aggregate), $sort, $project (reshape), $limit, $skip, $unwind (flatten arrays), and $lookup (join another collection).
$match and $group
js
// Count students per course, only enrolled ones
db.students.aggregate([
{ $match: { enrolled: true } },
{
$group: {
_id: "$course",
count: { $sum: 1 },
avgAge: { $avg: "$age" }
}
},
{ $sort: { count: -1 } }
]);Place $match and $sort (on indexed fields) as early in the pipeline as possible — this reduces the number of documents that later stages must process.
Ready to test yourself?
Practice MongoDB— quiz & coding exercises