Reference · Cheat sheet
Lesson 0005 distilled — stages over a document stream, $match early, and $lookup as the join to avoid. Built to print.
Ordered stages; each transforms a document stream and feeds the next (like Unix pipes).
A stage may add/drop/reshape docs. Read-only unless it ends in $out/$merge.
| Stage | SQL |
|---|---|
$match | WHERE |
$group | GROUP BY |
$project | SELECT list |
$sort | ORDER BY |
$limit/$skip | LIMIT/OFFSET |
$lookup | LEFT OUTER JOIN |
$unwind | ≈ UNNEST |
$match moved early — before $sort (less to sort) and before a projection (can hit an index) = predicate pushdown.
$sort + $limit coalesced → top-N, keep only N in memory.
Early $project to drop fields = unneeded; done automatically.
Left outer join to another collection (same DB); adds an array field of matched foreign docs.
Manual: "Excessive use of $lookup may slow down query performance… consider an embedded data model."
Heavy $lookup = your schema wants embedding (back to 0001).
Put $match (and a usable $sort) first so the opening stage uses an index — the first-stage index use you read in explain() (0004).
[ {$match}, {$group:{_id:"$city",n:{$sum:1}}}, {$sort:{n:-1}}, {$limit:5} ]
= active users per city, busiest 5 first.