How to Use $lookup in Aggregation in MongoDB
Use the
$lookup stage in a MongoDB aggregation pipeline to join documents from a foreign collection into the current collection. It requires specifying the foreign collection name, local field, foreign field, and the output array field to store matched documents.Syntax
The $lookup stage has this structure:
- from: The name of the foreign collection to join.
- localField: The field from the current collection to match.
- foreignField: The field from the foreign collection to match against.
- as: The name of the new array field to add matched documents.
json
{
$lookup: {
from: "<foreign_collection>",
localField: "<local_field>",
foreignField: "<foreign_field>",
as: "<output_array_field>"
}
}Example
This example joins the orders collection with the customers collection to add customer details to each order.
javascript
db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerDetails"
}
}
])Output
[
{
_id: 1,
item: "Pen",
quantity: 10,
customerId: 101,
customerDetails: [
{
_id: 101,
name: "Alice",
city: "New York"
}
]
},
{
_id: 2,
item: "Notebook",
quantity: 5,
customerId: 102,
customerDetails: [
{
_id: 102,
name: "Bob",
city: "Chicago"
}
]
}
]
Common Pitfalls
- Not matching the correct field types between
localFieldandforeignFieldcauses no matches. - Forgetting that
$lookupadds an array field, even if only one match exists. - Using
$lookupoutside an aggregation pipeline will cause errors.
javascript
/* Wrong: Using $lookup in a find query (invalid) */ db.orders.find({ $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "customerDetails" } }) /* Right: Use $lookup inside aggregate() */ db.orders.aggregate([ { $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "customerDetails" } } ])
Quick Reference
| Field | Description |
|---|---|
| from | Name of the foreign collection to join |
| localField | Field from the current collection to match |
| foreignField | Field from the foreign collection to match |
| as | Name of the new array field to store matched documents |
Key Takeaways
Use $lookup inside an aggregation pipeline to join collections in MongoDB.
Ensure localField and foreignField have matching data types for successful joins.
$lookup outputs an array field even if only one matching document exists.
Always specify the foreign collection name with the 'from' field.
Do not use $lookup in find queries; it only works in aggregate pipelines.