The aggregation pipeline
Stages transform a stream of documents one step at a time.
What you will be able to do
- Start with $match to reduce the working set.
- Use $group with explicit accumulators such as $sum and $avg.
- Inspect each stage with a small dataset before running at scale.
In plain English
$match filters early, $group aggregates, $lookup joins and $project shapes output. Put $match and $limit as early as possible so later stages process less data. Use $facet only when you need multiple summaries in one pass.
db.lessons.aggregate([
{ $match: { published: true } },
{ $group: {
_id: "$courseSlug",
lessons: { $sum: 1 },
minutes: { $sum: "$minutes" }
} },
{ $sort: { minutes: -1 } },
{ $limit: 5 }
])Your turn
MediumSummarize lessons by course
Aggregate published lessons by courseSlug and return lesson count and total minutes.
JAVASCRIPT · starter
db.lessons.aggregate([])Check your understanding before moving on.
Knowledge checkQuestion 1
Which stage groups documents by a key?
Select an answer to continue
Study tools
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign inFinished reading?
Lock in what you just learned.
0%
Mark this lesson complete to save your place and move one step closer to the certificate.