$lookup (Join Collections)
Last updated: 2026-10-09
$lookup (Join Collections)
$lookup performs a left outer join between the current collection and another collection, attaching matching documents as an array to each result. Equivalent to SQL LEFT JOIN, it lets pipelines combine data across collections without multiple queries. Note it only supports equality matches — no range or conditional joins.
| Category | Core Stages |
|---|---|
| MongoDB Version | 3.2+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $lookup: { from: <collection>, localField: <local-field>, foreignField: <foreign-field>, as: <output-array> } }
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $lookup: join orders with customers
db.orders.aggregate([
{ $lookup: {
from: "customers",
localField: "cust_id",
foreignField: "_id",
as: "customer"
} }
])
Output:
{ "_id": 1, "cust_id": "A123", "customer": [{ "_id": "A123", "name": "Alice" }] }
📌 Notes
- from must reference a collection in the same database
- Field names must match exactly and types must align between localField and foreignField
- No match yields an empty array [], not null
- Since 3.6, $lookup supports an inner pipeline (pipeline field) for richer joins; from 5.0 the concise correlated-subquery syntax drops the need for $expr
🏷️ Related Tags
💡 Related Cases
Advanced Aggregation Pipelines: Complex Expressions and Transformations
Introduction to Aggregate Pipelines: The `aggregate` Method and the Basic Stage
Hands-On: CRUD for a Blog Comment System
Databases and Collections: Namespace Management in MongoDB
Documents and BSON: The Cornerstone of MongoDB Data
$facet + $bucket + Text/Geospatial Search
$lookup and Associations with Multiple Sets
Mongoose Advanced Patterns: Performance and Flexibility
Mongoose Models and Schema Design
Mongoose Data Validation and Middleware
📚 Related Tutorials
❓ FAQ
QCan $lookup replace database-level JOINs?
AIt achieves similar results, but $lookup merges data at query time: equality matches and simple comparisons inside the pipeline can use indexes, yet its join optimization is less comprehensive than SQL databases, so evaluate performance on very large datasets.
QHow can I optimize $lookup performance?
ACreate an index on the foreign key field of the joined collection. Also prefer $match early in the pipeline to shrink the main collection before the join.
QDoes $lookup support multi-key joins?
AYes. Since 3.6, the pipeline form of $lookup with $expr enables multi-field joins and subqueries beyond simple equality on one key.