Question 19 / 50
What does $lookup do, and why is it sometimes expensive?
Short answer
It is a left outer join: matching documents from another collection are attached as an array. It can be expensive because it runs per input document, the joined array counts toward the 16MB limit, and a missing index on the foreign field turns each lookup into a scan.
Why?
Non-matching parents still come through with an empty array. $match before $lookup shrinks the input set — usually the biggest win. A frequent $lookup is often a signal the two entities should have been embedded, or that the read should be two targeted queries in the app.
Example
db.users.aggregate([
{
$lookup: {
from: "orders",
localField: "_id",
foreignField: "userId",
as: "orders"
}
}
])Interview tip
If asked about joins in MongoDB, mention that a hot join is often a modelling smell, not just a missing index.
Common mistake
Looking up orders for every user on a list page with no $match and no index on orders.userId.
How did you do?