Most Developers Use $lookup… But Don’t Know How It Actually Works
Scenario: eCommerce Website
Maan lo tum MERN stack se ek online store bana rahe ho.
Tumhare paas do collections hain:
1️⃣ Users Collection
[
{ "_id": 1, "name": "Rahul" },
{ "_id": 2, "name": "Amit" }
]2️⃣ Orders Collection
[
{ "orderId": 101, "userId": 1, "product": "Laptop" },
{ "orderId": 102, "userId": 1, "product": "Mouse" },
{ "orderId": 103, "userId": 2, "product": "Keyboard" }
]Ab tum frontend me user profile page bana rahe ho jahan dikhana hai:
User + uske saare orders
MongoDB Query:
db.users.aggregate([
{
$lookup: {
from: "orders",
localField: "_id",
foreignField: "userId",
as: "orders"
}
}
])Step-by-Step Internally Kya Ho Raha Hai
Step 1 — MongoDB Users Collection Scan karta hai
Server users collection se ek document uthata hai.
Example:
user = { _id: 1, name: "Rahul" }Step 2 — Join Key Identify karta hai
MongoDB dekhta hai:
localField = _id
foreignField = userIdMatlab match condition:
users._id == orders.userIdStep 3 — Orders Collection me Matching Data Dhundta hai
MongoDB orders collection me check karta hai:
order.userId == 1Matching documents:
{ orderId: 101, userId: 1, product: "Laptop" }
{ orderId: 102, userId: 1, product: "Mouse" }Step 4 — Result Attach karta hai
MongoDB un orders ko array me attach kar deta hai.
Result:
{
"_id": 1,
"name": "Rahul",
"orders": [
{ "orderId": 101, "userId": 1, "product": "Laptop" },
{ "orderId": 102, "userId": 1, "product": "Mouse" }
]
}Agar Dataset Bada Ho
Agar millions of orders ho, MongoDB slow loop nahi karta.
Get PRAJJAL DHAR’s stories in your inbox
Join Medium for free to get updates from this writer.
Instead:
Hash Map Banata Hai
Conceptually:
hashMap = {
1: [order101, order102],
2: [order103]
}Fir:
user._id → hashMap[user._id]Yeh C++ hash table / unordered_map style lookup jaisa hota hai.
Agar Index Ho
Agar orders.userId indexed ho:
db.orders.createIndex({ userId: 1 })To MongoDB:
direct index lookup karta haiFull collection scan nahi karta.
Real Developer Mental Model
MERN developer ke liye $lookup ko aise socho:
JavaScript Version
const orderMap = orders.reduce((acc, order) => {
if (!acc[order.userId]) acc[order.userId] = []
acc[order.userId].push(order)
return acc
}, {})Fir:
users.map(user => ({
...user,
orders: orderMap[user._id] || []
}))Composite indexing ka matlab hota hai ek se zyada fields par index banana taaki multi-field queries fast ho jayein. MongoDB me yeh compound index ke naam se bhi jana jata hai.
Orders Collection (Large Dataset)
Maan lo tumhare paas ek orders collection hai jisme kaafi fields hain.
[
{
"_id": 101,
"userId": 1,
"productId": 501,
"productName": "Gaming Laptop",
"category": "Electronics",
"brand": "Asus",
"price": 95000,
"quantity": 1,
"city": "Delhi",
"status": "delivered",
"paymentMethod": "UPI",
"orderDate": "2026-03-01"
},
{
"_id": 102,
"userId": 1,
"productId": 502,
"productName": "Wireless Mouse",
"category": "Electronics",
"brand": "Logitech",
"price": 1200,
"quantity": 2,
"city": "Delhi",
"status": "delivered",
"paymentMethod": "Card",
"orderDate": "2026-03-02"
},
{
"_id": 103,
"userId": 2,
"productId": 503,
"productName": "Mechanical Keyboard",
"category": "Electronics",
"brand": "Keychron",
"price": 8500,
"quantity": 1,
"city": "Mumbai",
"status": "processing",
"paymentMethod": "UPI",
"orderDate": "2026-03-03"
},
{
"_id": 104,
"userId": 3,
"productId": 504,
"productName": "iPhone 15",
"category": "Mobiles",
"brand": "Apple",
"price": 79000,
"quantity": 1,
"city": "Bangalore",
"status": "shipped",
"paymentMethod": "Card",
"orderDate": "2026-03-04"
},
{
"_id": 105,
"userId": 2,
"productId": 505,
"productName": "Noise Cancelling Headphones",
"category": "Electronics",
"brand": "Sony",
"price": 22000,
"quantity": 1,
"city": "Mumbai",
"status": "delivered",
"paymentMethod": "NetBanking",
"orderDate": "2026-03-05"
}
]Problem
Agar tum frequently query karte ho:
- userId
- status
- orderDate
Example query:
db.orders.find({
userId: 2,
status: "delivered"
})Ya:
db.orders.find({
userId: 1,
status: "delivered",
city: "Delhi"
})Agar index nahi hai to MongoDB collection scan karega.
Composite Index Create Karna
db.orders.createIndex({
userId: 1,
status: 1,
city: 1
})Yeh compound index hai.
Index Structure Conceptually
Internally index roughly aise store hota hai:
{
(1, "delivered", "Delhi") → order101
(1, "delivered", "Delhi") → order102
(2, "processing", "Mumbai") → order103
(3, "shipped", "Bangalore") → order104
(2, "delivered", "Mumbai") → order105
}Yeh basically multi-key sorted structure hota hai (B-tree).
Query Execution
Query:
db.orders.find({
userId: 2,
status: "delivered",
city: "Mumbai"
})MongoDB directly index me search karega:
(2,"delivered","Mumbai")Aur result instantly mil jayega.
Kaise Verify Kare ki Index Use Ho Raha Hai
MongoDB me:
db.orders.find({
userId: 1,
city: "Delhi",
status: "delivered"
}).explain("executionStats")Output me dikhega:
IXSCANMatlab:
Index ScanAgar dikhe:
COLLSCANMatlab:
Collection ScanIndex use nahi hua.
Query Planner Indexes Check karta hai
MongoDB system catalog me dekhta hai ki orders collection par kaunse indexes hain.
Example:
db.orders.getIndexes()Output example:
[
{ key: { _id: 1 } },
{ key: { userId: 1, city: 1, status: 1 } }
]Query planner dekhta hai:
kya koi index hai jo in fields ko cover karta hai?Mental Model: $lookup = 4 Questions
Jab bhi $lookup likho, bas 4 sawaal pucho.
1. Data kahan se lana hai?
2. Kis field se match karna hai?
3. Kis field se compare karna hai?
4. Result kis naam se store karna hai?Pattern (Simple Join)
Is model ko follow karo:
{
$lookup: {
from: "collection2",
localField: "field_in_current_collection",
foreignField: "field_in_foreign_collection",
as: "resultArray"
}
}db.users.aggregate([
{
$lookup: {
from: "orders",
let: { userId: "$_id", userCity: "$city" },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ["$userId", "$$userId"] },
{ $eq: ["$city", "$$userCity"] },
{ $eq: ["$status", "delivered"] }
]
}
}
}
],
as: "orders"
}
}
])






