Joins, facets and window functions
The aggregation pipeline can do almost anything a SQL report can: join collections, compute several reports in one pass, bucket values into ranges, and calculate running totals and rankings.
$lookup: joining collections
Orders store a customerId. $lookup fetches the matching customer documents into an array field:
customer is an array (a lookup can match many documents). When you expect exactly one, $unwind it, then pick the fields you want:
Top customers by spend
Group first (fewer documents), then look up names, which is much cheaper than looking up every order:
Customers with no orders
A lookup that finds nothing gives an empty array, which makes "anti-joins" easy:
⚠️
$lookupis useful, but if you find yourself joining on every request, the data might belong embedded in one document. That's the next lesson's topic.
$facet: several reports in one query
$facet runs several sub-pipelines on the same input and returns all the results together. It's perfect for search pages that show results plus counts per filter:
$bucket: grouping into ranges
$bucketAuto picks boundaries for you, given a number of buckets.
Window functions: $setWindowFields
Window functions compute values across related documents without collapsing them into groups: running totals, rankings, moving averages.
Running total
window: { documents: ['unbounded', 'current'] } means "from the first document up to this one".
Ranking within groups
partitionBy restarts the calculation for each group, like PARTITION BY in SQL:
That's "the most expensive product in each category" in one pipeline.
Working with arrays inside documents
You don't always need $unwind. Array expressions work on each document's arrays directly:
Inside $filter and $map, $$i refers to the current element (a variable named by as).
Practice
- Join orders to customers and compute total revenue per country.
- Use
$facetto return, in one query, the number of orders per status and the 2 most recent orders. - Rank customers by age within each country using
$setWindowFields.
1.What does $lookup add to each document?
2.Which stage computes several independent reports over the same input in one query?
3.How do window functions differ from $group?