Lesson 17 +10 XP

Aggregation Pipelines

Aggregation Pipelines

Aggregation lets you group, sort, calculate, and analyze data. You do it by building a pipeline of stages - each stage transforms the results of the previous stage.

The aggregate() method

db.posts.aggregate([
  // Stage 1: only documents with more than 1 like
  { $match: { likes: { $gt: 1 } } },
  // Stage 2: group by category and sum each category's likes
  { $group: { _id: "$category", totalLikes: { $sum: "$likes" } } }
])

How it works

  • The pipeline is an array of stages.
  • Each stage processes the documents coming from the previous stage.
  • Order matters - a $sort before a $limit gives different results than after.

Field references use $

Inside a stage, a field reference starts with $ - like "$category" or "$likes". This tells MongoDB "use the value of this field."

Why aggregations?

  • Calculate totals, averages, and counts.
  • Group data by categories.
  • Join data across collections ($lookup).
  • Shape and reshape documents for reporting.

Common stages

StageWhat it does
$matchFilters documents
$sortOrders documents
$projectPicks fields to keep
$limitLimits how many documents pass
$groupGroups documents by a key
$countCounts documents
$addFieldsAdds new computed fields
$lookupJoins another collection
$outWrites results to a collection

TL;DR

  • Aggregation = a pipeline of stages passed to aggregate().
  • Each stage transforms the previous stage's output; order matters.
  • Field references inside stages use a $ prefix.