Problem Statement
Explain how to use $lookup to join collections in MongoDB aggregation. When should you avoid using $lookup?
Explanation
The dollar lookup stage performs a left outer join between the current collection and another collection in the same database. It requires four parameters: from specifies the target collection to join, localField is the field from the input documents, foreignField is the field from the documents in the from collection, and as is the output array field name.
Dollar lookup adds a new array field to each input document containing all matching documents from the joined collection. If no matches are found, the array is empty. You can use dollar unwind after dollar lookup to flatten the results if you expect one-to-one relationships.
However, you should avoid using dollar lookup when possible because joins are expensive operations. MongoDB is designed for embedded documents, not relational joins. If you frequently need to join collections, consider embedding the data instead.
Use dollar lookup only when data is truly independent and shared across many documents, when the joined data is rarely needed, or when the joined collection is small. For frequently accessed related data, embedding is more efficient as it retrieves everything in a single query without joins.
Code Solution
SolutionRead Only
// Basic $lookup
db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerDetails"
}
}
])
// With unwind for one-to-one
db.orders.aggregate([
{ $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "customer" } },
{ $unwind: "$customer" }
])
// Better approach: Embed data
{
orderId: 1,
customer: { name: "John", email: "john@example.com" },
items: [...]
}