$lookup (joins)
$lookup performs a left outer join with another collection in the same database.
In this page:
Syntax
{ $lookup: {
from: "other_collection",
localField: "local_field",
foreignField: "foreign_field",
as: "result_array"
} }
$lookup (joins)
$lookup takes from, localField, foreignField and as, and adds an array of matching foreign documents to each input document.
An empty array means no match. Pair it with $unwind to flatten the array.
Frequent joins may suggest embedding the data instead.
Note:
Index the foreignField for fast lookups.
Example: $lookup (joins)
test> db.customers.insertMany([{ _id: 1, name: "Ada" }, { _id: 2, name: "Bob" }])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2 } }
test> db.orders.insertMany([{ _id: 10, customerId: 1, total: 50 }, { _id: 11, customerId: 1, total: 20 }, { _id: 12, customerId: 3, total: 5 }])
{ acknowledged: true, insertedIds: { '0': 10, '1': 11, '2': 12 } }
test> db.orders.aggregate([
... { $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "customer" } },
... { $project: { total: 1, customer: "$customer.name" } }
... ])
[
{ _id: 10, total: 50, customer: [ 'Ada' ] },
{ _id: 11, total: 20, customer: [ 'Ada' ] },
{ _id: 12, total: 5, customer: [] }
]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Forgetting the result is an array
- Missing an index on foreignField
- Using joins everywhere instead of good schema design
Chapter Summary
- $lookup joins collections
- from, localField, foreignField, as
- Result is an array
- Index the foreign field
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: