$lookup performs a left outer join to another collection—use indexed foreign keys.
Basic lookup
db.orders.aggregate([
{ $lookup: {
from: 'customers',
localField: 'customerId',
foreignField: '_id',
as: 'customer'
}},
{ $unwind: '$customer' },
{ $project: { total: 1, 'customer.name': 1 } }
])Practice: Run aggregation pipelines in mongosh.
Pipeline lookup (modern)
db.orders.aggregate([
{ $lookup: {
from: 'customers',
let: { cid: '$customerId' },
pipeline: [
{ $match: { $expr: { $eq: ['$_id', '$$cid'] } } },
{ $project: { name: 1 } }
],
as: 'customer'
}}
])
Important interview questions and answers
- Q: $unwind after lookup?
A: Expands array—empty arrays drop doc unless preserveNullAndEmptyArrays. - Q: Index foreignField?
A: Index _id or customerId to avoid slow joins.
Self-check
- What does as: 'customer' create?
- Why index customerId on orders?
Tip: Index localField and foreignField used in $lookup.
Interview prep
- $lookup?
- Left outer join to another collection.
- $unwind?
- Deconstructs array field into one doc per element.