Loading Depth Study
Preparing your workspace
The aggregation pipeline processes documents through a sequence of stages to produce calculated or transformed results.
Aggregation is useful when an application needs more than a simple query. Pipeline stages such as $match, $group, $project, $sort, $limit, and $lookup can filter, calculate, reshape, and combine data. Each stage passes its output to the next stage. Aggregation is especially useful for reports, dashboards, analytics, and grouped statistics. Good pipelines filter early when possible and return only the information the application needs.
An admin dashboard can calculate how many students completed each course and sort courses by completion count.
const results = await db.collection("enrollments").aggregate([
{
$match: { completed: true }
},
{
$group: {
_id: "$courseId",
completedCount: { $sum: 1 }
}
},
{
$sort: { completedCount: -1 }
}
]).toArray();
console.log(results);The aggregation returns courses grouped by ID with the number of completed enrollments, sorted from highest to lowest.