Aggregation Pipeline Architecture: $match, $group, $project & $sort0%
Aggregation Pipeline Architecture: $match, $group, $project & $sort
Beginner12 min read•Updated: Jul 11, 2026
Aggregation Pipeline Architecture: $match, $group, $project & $sort
While .find() is ideal for simple document retrieval, complex data analytics, reports, metric calculations, and data transformations require the MongoDB Aggregation Pipeline. Documents pass through a multi-stage pipeline where each stage transforms the data stream sequentially.
1. The Pipeline Concept
Think of the aggregation pipeline as an industrial assembly line:
Output
Raw Collection ---> [$match] ---> [$project] ---> [$group] ---> [$sort] ---> Final Report
The output of each stage serves as the input to the next stage.
2. The Core Pipeline Stages
$match: Filters documents (analogous to SQLWHERE). Place this as early as possible in the pipeline to utilize indexes and reduce data volume for subsequent stages!$project: Reshapes documents: adds computed fields, renames fields, or excludes existing fields (analogous to SQLSELECT).$group: Groups documents by a specified identifier key and performs accumulative calculations like sum, average, min, max (analogous to SQLGROUP BY).$sort: Sorts the resulting stream of documents (analogous to SQLORDER BY).
3. Real-World Aggregation: Course Revenue & Rating Analytics
Calculate statistics for all published courses grouped by category:
JavaScript
const categoryStats = await Course.aggregate([
// Stage 1: Filter only published courses
{
$match: { isPublished: true, rating: { $gte: 4.0 } }
},
// Stage 2: Group by category and compute aggregate metrics
{
$group: {
_id: '$category', // Grouping key ($ prefix denotes field reference)
totalCourses: { $sum: 1 }, // Count documents
avgPrice: { $avg: '$price' },
minPrice: { $min: '$price' },
maxPrice: { $max: '$price' },
totalEnrollments: { $sum: '$enrollmentCount' }
}
},
// Stage 3: Reshape output and round decimals
{
$project: {
category: '$_id',
_id: 0, // Exclude raw _id
totalCourses: 1,
totalEnrollments: 1,
avgPrice: { $round: ['$avgPrice', 2] },
priceRange: {
$concat: ['$', { $toString: '$minPrice' }, ' - $', { $toString: '$maxPrice' }]
}
}
},
// Stage 4: Sort by total revenue/enrollments descending
{
$sort: { totalEnrollments: -1 }
}
]);
console.log(categoryStats);
Interactive Quiz
Multiple Choice Questions
Question 1
In MongoDB Aggregation, what does the
$match stage do?Question 2
Why is placing the
$match stage at the very beginning of an aggregation pipeline considered a best practice?Question 3
In the
$group stage, how do you reference the value of an existing document field named category?Question 4
Which accumulator operator computes the total count of documents inside a
$group stage?Question 5
What does setting
_id: 0 in a $project stage accomplish?Next Lesson
Multi-Table Joins with $lookup & Array Flattening with $unwind
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.