MongoDB Aggregation $lookup

MongoDB Aggregation $lookup
In MongoDB Aggregation $lookup is used to join data from another collection during aggregation.
Think of $lookup as:
LEFT OUTER JOIN in SQL
What is $lookup?
Joins two collections
Combines documents based on a matching field
Output is an array field containing matched documents
1️⃣ Basic Syntax
2️⃣ Simple Example (Most Common)
Scenario
You have:
orderscollectioncustomerscollection
You want customer details with each order.
orders Collection
customers Collection
$lookup Query
Output
3️⃣ Why Output is an Array? (Interview Question)
✔ One document can match multiple documents
✔ MongoDB always returns an array
Even if only one match exists, it’s still an array.
4️⃣ $lookup + $unwind (Very Important)
To convert array into object:
This gives flat, readable output.
5️⃣ $lookup with $match (Filter Joined Data)
6️⃣ $lookup with Pipeline (Advanced / Interview)
Used when:
Complex conditions
Multiple fields
Expressions
7️⃣ $lookup vs SQL JOIN
| SQL | MongoDB |
|---|---|
JOIN | $lookup |
| Tables | Collections |
| Rows | Documents |
| Result | Joined rows |
8️⃣ Performance Notes (Interview Tip)
✔ Index foreignField
✔ Avoid large collections
✔ Use $match before $lookup
✔ Prefer embedding for frequent joins
Key Points (Very Important for Exams & Interviews)
✔ $lookup joins two collections
✔ Works like LEFT OUTER JOIN
✔ Output is always an array
✔ $unwind flattens the result
✔ Pipeline $lookup is most powerful
Common Interview Questions
Q1. What is $lookup in MongoDB?
👉 Used to join collections
Q2. Which SQL join is $lookup similar to?
👉 LEFT OUTER JOIN
Q3. Why does $lookup return an array?
👉 To support multiple matches
Q4. How to convert array to object?
👉 Using $unwind
Summary
That’s everything you need to know about MongoDB Aggregation
$lookup.
