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":
Step by step:
- $match keeps only the documents you care about (it uses the same filters as
find). - $group combines documents with the same
_id. Here_id: '$status'means "one group per status".$sum: 1counts the documents;$sum: '$total'adds up thetotalfield. - $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:
| 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 |
$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:
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:
Now group by product to find bestsellers:
Grouping by date
The _id of a group can also be an object, for grouping by several fields: _id: { month: { $month: '$createdAt' }, status: '$status' }.
Counting shortcuts
Pipeline performance tips
- Put
$match(and$limit) as early as possible so later stages process fewer documents. A$matchat the very start can use indexes, just likefind. $projectearly 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:
$out replaces the target collection; $merge updates or inserts into it, so you can refresh a report incrementally.
Practice
- Find the average product price per category, rounded to 2 decimals (
$round: ['$avgPrice', 2]in a later stage). - Count customers per country (
'$address.country'). - List the top 3 products by number of orders they appear in (hint:
$unwind, then$groupwith$sum: 1).
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?