Embedded vs Referenced DataIntermediate
1Question 1 of 1
javascriptHow does the $lookup stage perform joins between collections in MongoDB?
Explanation & Concept
The `$lookup` aggregation stage performs an equality join between two collections, appending matching documents from the foreign collection into an array field of the input document.
It is MongoDB's equivalent to an SQL `LEFT OUTER JOIN`.
Code Example
javascript
db.orders.aggregate([
{
$lookup: {
from: "customers", // Foreign collection
localField: "customerId", // Field in orders
foreignField: "_id", // Field in customers
as: "customerDetails" // Output array field name
}
},
// Flatten single-element array to object
{
$unwind: {
path: "$customerDetails",
preserveNullAndEmptyArrays: true
}
}
]);How It Works & Key Takeaways
`$lookup` matches `orders.customerId` against `customers._id`. Using `$unwind` transforms the resulting one-element array into a flat sub-object on each order document.
Mock Test · 1 Questions · Optional
Ready for Mongoose Basics?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions