Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

MDB
MongoDB
0/10 completed
Beginner
What is MongoDB?Inserting and finding documentsUpdating and deleting
Intermediate
Query operatorsSorting, paging and projectionIndexes and explain()
Advanced
The aggregation pipelineJoins, facets and window functionsSchema design and validation
Pro
Drivers, transactions and scaling
Tracks / MongoDB / Advanced

The aggregation pipeline

find returns documents. When you need to calculate something (totals, averages, rankings, reports), you use the aggregation pipeline: a list of stages, where each stage transforms the stream of documents and passes the result to the next.

orders ─▶ $match ─▶ $group ─▶ $sort ─▶ $limit ─▶ results
          (filter)  (combine) (order)  (top N)

Your first pipeline

"Revenue per order status, highest first, ignoring cancelled orders":

MongoDB shell (simulated) · editable

Step by step:

  1. $match keeps only the documents you care about (it uses the same filters as find).
  2. $group combines documents with the same _id. Here _id: '$status' means "one group per status". $sum: 1 counts the documents; $sum: '$total' adds up the total field.
  3. $sort orders the groups.

A $ before a field name ('$status') means "the value of this field".

$group in depth

The _id of $group decides the groups. null puts everything into one group:

MongoDB shell (simulated) · editable
Accumulator Gives
$sum, $avg, $min, $max Arithmetic over the group
$count: {} Number of documents
$first, $last First/last value (sort before grouping!)
$push An array of all values
$addToSet An array of unique values
MongoDB shell (simulated) · editable

$project and $addFields: reshaping documents

$project chooses and computes fields (like a projection in find). $addFields (alias $set) adds fields and keeps all the others:

MongoDB shell (simulated) · editable

Expressions you'll use often: $add, $subtract, $multiply, $divide, $round, $concat, $toUpper, $cond (if/then/else), $ifNull, $size, $dateToString.

$unwind: one document per array element

Each order has an items array. To analyse products sold, you need one document per item. $unwind does exactly that:

MongoDB shell (simulated) · editable

Now group by product to find bestsellers:

MongoDB shell (simulated) · editable

Grouping by date

MongoDB shell (simulated) · editable

The _id of a group can also be an object, for grouping by several fields: _id: { month: { $month: '$createdAt' }, status: '$status' }.

Counting shortcuts

MongoDB shell (simulated) · editable

Pipeline performance tips

  • Put $match (and $limit) as early as possible so later stages process fewer documents. A $match at the very start can use indexes, just like find.
  • $project early to drop large fields you don't need.
  • Each stage has a 100 MB memory limit; big sorts and groups can spill to disk.
  • Use explain() on aggregations too: db.orders.explain().aggregate([...]) on a real server.

Saving results: $out and $merge

A pipeline can write its results to a collection, which is great for pre-computed reports:

MongoDB shell (simulated) · editable

$out replaces the target collection; $merge updates or inserts into it, so you can refresh a report incrementally.

Practice

  1. Find the average product price per category, rounded to 2 decimals ($round: ['$avgPrice', 2] in a later stage).
  2. Count customers per country ('$address.country').
  3. List the top 3 products by number of orders they appear in (hint: $unwind, then $group with $sum: 1).
MongoDB shell (simulated) · editable
✎ Check your understanding

1.In { $group: { _id: '$status', n: { $sum: 1 } } }, what does $sum: 1 do?

2.Why put $match at the start of a pipeline?

3.What does $unwind: '$items' do to an order with 3 items?

← Indexes and explain()