Skip to content
Tutorials Center
My learning

Topics

Lesson 68 of 70 ยท Practice and wrap-up

Practice: Aggregation Exercises

Fifteen MongoDB aggregation exercises, from $group and $project to $unwind, $lookup and $facet, each with a full runnable pipeline solution and an explanation.

Aggregation pipelines are best learned by building them. This lesson gives you fifteen exercises on a small online shop, in rising difficulty: counting and grouping first, then computed fields, arrays, joins and finally a multi-report $facet. Every exercise has a complete solution that you can run, and a short note on why it is written that way.

The pipelines run on the tutorial's practice engine, a plain JavaScript stand-in (see The Practice Engine Used in This Tutorial). The stage and expression documents are what you would pass to db.orders.aggregate([...]) in mongosh, but the engine supports only a subset of MongoDB's stages and operators, and it returns groups in the order it meets them, whereas real MongoDB promises no order after $group. That is why most solutions end with an explicit $sort: do the same in your own code.

Pipeline checklist

$match first Shrink the data early.
$group once Pick a key, add accumulators.
$sort the result Group order is not promised.
$project last Shape the final output.
1 / 2

The data

Two collections. customers has six documents with _id, name and country. orders has twelve documents, each with a customerId, a createdAt date, a status (paid, refunded, cancelled or pending), an items array of { sku, category, qty, price } line items, and a stored total. Customer c6 (Tom Berg) has never ordered. All dates are fixed, so every answer below is deterministic. The code at the top of each TryIt builds both collections; the helper order(...) computes each total from its items.

Part 1: grouping and shaping (exercises 1 to 8)

  1. Count the orders in each status, most frequent first.
  2. What is the total revenue of paid orders? (One document, no key.)
  3. Average paid order total per customer, rounded to 2 decimals, sorted by customer id.
  4. The three largest paid orders: only _id and total.
  5. List customers per country: the country and an array of names, sorted by country.
  6. Paid revenue and order count per month (YYYY-MM), oldest month first.
  7. Label each paid order big (total of 100 or more) or small, and count orders per label.
  8. Units sold per SKU in paid orders, best-selling first.

Two reminders before you start. A $group with _id: null collapses everything into one document, the aggregation version of SUM(...) over a whole table. And $sum: 1 counts documents. Run the solutions and compare:

JS Exercises 1 to 8: solutions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notes on part 1

In exercise 1 the second sort key (_id: 1) breaks ties, so ties between statuses always come out in the same order; without it the order of equal counts is not defined. Exercise 2 shows that the result of a global total is an array holding one document, so in application code you read result[0]?.revenue ?? 0: with an empty input $group returns no document at all, not a zero.

Exercise 3 puts $round inside $project, because $avg cannot also round: accumulators belong to $group, per-document expressions belong to $project or $addFields. In exercise 4, order matters: sort, then limit, then project. Reversing sort and limit would cut arbitrary documents first. Exercise 5 uses $push; with $addToSet you would get unique names, in no particular order.

Exercise 7 is the pattern for "bucketing by a condition": compute a label with $cond in $addFields, then group on the label. And exercise 8 needs $unwind because the SKU lives inside the items array: before the unwind the document is an order, after it the document is a line item.

Part 2: arrays, joins and reports (exercises 9 to 15)

  1. Paid revenue per category (qty * price), largest first.
  2. Find orders (any status) with more than two line items. Show _id and the item count.
  3. Show each paid order's _id together with the customer's name (join with customers).
  4. Paid revenue per customer country, largest first.
  5. Build a single report with $facet: the paid-order count and average total, the order count per status, and the top two SKUs by units in paid orders.
  6. Which categories appear in the most line items across all orders (any status)?
  7. List the customers who have never placed an order.
JS Exercises 9 to 15: solutions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notes on part 2

Exercise 10 counts array elements with $size after $addFields; real MongoDB also lets you write { $match: { "items.2": { $exists: true } } }, which tests whether a third element exists. Exercise 11 uses $arrayElemAt because $lookup always produces an array, even when exactly one document matches; the alternative is $unwind, which turns the single-element array into a plain subdocument (exercise 12). An unwound lookup drops documents with no match, which is a good thing for an inner join and a bug for a left join: add preserveNullAndEmptyArrays: true when you need left-join behaviour.

Exercise 12 is the "group, then join" idea in reverse: because the country lives on the customer, the join must come first. When the group key is on the same collection, join after grouping to look up fewer rows (see Project: Sales Analytics Pipelines).

Exercise 13: a $facet returns one document whose fields are arrays, which is why paid is read as report.paid[0]. Each sub-pipeline starts from the same input, so a $match inside a facet applies only to that facet. Exercise 14 shows $sortByCount as shorthand for group, count and sort, after an $unwind so that each line item counts once. Exercise 15 finds missing relationships by joining and keeping the empty ones; it works, but on a large collection you would index orders.customerId (so each lookup is an index probe) or store an orderCount on the customer.

Beyond the exercises

Once your pipelines are correct, check three things. First, put $match and $sort early so that an index can serve them (see Aggregation Performance and Explain). Second, test each pipeline against a tiny fixture with known answers, just as these exercises do. Third, remember that the stand-in is forgiving: real MongoDB is stricter about stage syntax, will not let a $facet result exceed 16 MB, and limits the memory of blocking stages such as $group and $sort (100 MB per stage), spilling to disk only where allowDiskUse is enabled (MongoDB 6.0 and later enable it by default).

A good extra challenge is to take any exercise and rebuild it in a second way: for example exercise 6 with $bucket-style date ranges, or exercise 11 with $unwind instead of $arrayElemAt. Two correct pipelines for the same question teach you more about the stages than one.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a $group stage with _id: null produce?

    A null group key puts every document in one group, like an aggregate function over a whole table. With no input documents it produces nothing at all.
  2. 2. Why does a $lookup result need $arrayElemAt or $unwind?

    The 'as' field always holds an array of matching documents. $arrayElemAt picks one element, and $unwind turns the array into one document per match.
  3. 3. In which order should these stages run to get the top 3 orders by total?

    Sort first so that the largest documents come first, then cut to three. Limiting first would keep arbitrary documents.
  4. 4. Why is the shop's pipeline for exercise 8 using $unwind before $group?

    After $unwind each document is one line item, so $group can total qty per SKU.

Summary

  • Fifteen pipelines covered $group, $project, $addFields, $cond, $unwind, $lookup, $sortByCount and $facet.
  • Always add an explicit $sort after $group; group order is not guaranteed in real MongoDB.
  • Sort before limit, and match before you unwind or join.
  • $lookup yields arrays: pick with $arrayElemAt or flatten with $unwind (use preserveNullAndEmptyArrays for left-join behaviour).
  • $facet returns one document of arrays, ideal for dashboards and summaries.
  • Test pipelines on small fixtures with answers you can check by hand.

Test what you remember in MongoDB Interview Questions.