Problem Statement
What does the $lookup stage do in MongoDB aggregation?
Explanation
The dollar lookup stage performs a left outer join between the current collection and another collection in the same database. It adds an array field containing matching documents from the joined collection.
This is similar to SQL joins but returns results as embedded arrays. Use dollar lookup when you need to combine data from multiple collections. However, overusing it can impact performance, so consider embedding data when appropriate instead of always using references and lookups.
Code Solution
SolutionRead Only
// Join orders with customer details
db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerInfo"
}
}
])
// Result includes customerInfo array