MongoDB Foundations·Documents with discipline

The aggregation pipeline

Stages transform a stream of documents one step at a time.

Beginner 15 min read Lesson 9 of 300 Challenge included
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.

pipeline.jsJavaScript
db.lessons.aggregate([
  { $match: { published: true } },
  { $group: {
      _id: "$courseSlug",
      lessons: { $sum: 1 },
      minutes: { $sum: "$minutes" }
  } },
  { $sort: { minutes: -1 } },
  { $limit: 5 }
])
Your turn

Summarize lessons by course

Medium

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 in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 9 of 300 · 0% of course