1.$lookup for collection joins
$lookup is an aggregation stage that joins documents from another collection into the current one, attaching the matches as a new array field. It is how MongoDB reaches across collections when embedding was not chosen for that relationship.
Key features
- $lookup runs against a second collection, matching a local field to a foreign field
- The joined documents are always attached as a new array field, even when only one match exists
- It always behaves like a LEFT OUTER JOIN: an input document with no matches still survives, with an empty array
- The foreign collection must be in the same database (or use a sharded-cluster-aware form) — $lookup cannot join across separate deployments
- A joined array of matches usually needs $unwind right after it, if the pipeline expects one match per input document
- orders — local collection
- leads to $lookup (localField)
- $lookup — match customerId = _id
- leads to order + customer[] (attaches as array)
- customers — foreign collection
- leads to $lookup (foreignField)
- order + customer[] — array field, even if 0 or 1 match
Command
{ $lookup: { from, localField, foreignField, as } }$lookup is a left outer join across collections — every input document survives, matches always land as an array field, and an unmatched document gets an empty array rather than being dropped.