0
0
MongoDBquery~10 mins

$lookup for joining collections in MongoDB - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - $lookup for joining collections
Start with main collection
For each document in main
Use $lookup to find matching docs in foreign collection
Add matched docs as array field
Output enriched documents
End
The $lookup stage takes each document from the main collection, finds matching documents in another collection, and adds them as an array field to enrich the original document.
Execution Sample
MongoDB
db.orders.aggregate([
  {
    $lookup: {
      from: "products",
      localField: "product_id",
      foreignField: "_id",
      as: "product_details"
    }
  }
])
This query joins 'orders' with 'products' by matching 'product_id' in orders to '_id' in products, adding matching product info as 'product_details'.
Execution Table
StepCurrent Document (orders)Lookup ConditionMatched Documents (products)Output Document
1{"_id": 1, "product_id": 101, "quantity": 2}product_id=101 matches _id in products[{"_id": 101, "name": "Pen", "price": 1.5}]{"_id": 1, "product_id": 101, "quantity": 2, "product_details": [{"_id": 101, "name": "Pen", "price": 1.5}]}
2{"_id": 2, "product_id": 102, "quantity": 1}product_id=102 matches _id in products[{"_id": 102, "name": "Notebook", "price": 3.0}]{"_id": 2, "product_id": 102, "quantity": 1, "product_details": [{"_id": 102, "name": "Notebook", "price": 3.0}]}
3{"_id": 3, "product_id": 999, "quantity": 5}product_id=999 does not match _id in products[]{"_id": 3, "product_id": 999, "quantity": 5, "product_details": []}
4No more documentsN/AN/AAggregation ends
💡 All documents in 'orders' processed; aggregation completes.
Variable Tracker
VariableStartAfter 1After 2After 3Final
Current DocumentN/A{"_id":1,"product_id":101,"quantity":2}{"_id":2,"product_id":102,"quantity":1}{"_id":3,"product_id":999,"quantity":5}No more documents
Matched DocumentsN/A[{"_id":101,"name":"Pen","price":1.5}][{"_id":102,"name":"Notebook","price":3.0}][]N/A
Output DocumentN/A{"_id":1,"product_id":101,"quantity":2,"product_details":[{"_id":101,"name":"Pen","price":1.5}]}{"_id":2,"product_id":102,"quantity":1,"product_details":[{"_id":102,"name":"Notebook","price":3.0}]}{"_id":3,"product_id":999,"quantity":5,"product_details":[]}Aggregation ends
Key Moments - 3 Insights
Why does the 'product_details' field contain an array even if only one product matches?
Because $lookup always adds matched documents as an array, even if there is only one or zero matches, as shown in execution_table rows 1 and 3.
What happens if no matching documents are found in the foreign collection?
The matched documents array is empty, so the new field contains an empty array, as seen in execution_table row 3.
Does $lookup modify the original documents in the main collection?
No, it outputs new documents with an added field; the original documents remain unchanged, as shown by the output documents in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 2. What is the value of 'product_details' in the output document?
A[{"_id": 102, "name": "Notebook", "price": 3.0}]
B[]
C[{"_id": 101, "name": "Pen", "price": 1.5}]
Dnull
💡 Hint
Check the 'Matched Documents' and 'Output Document' columns at Step 2 in the execution_table.
At which step does the lookup find no matching documents?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look for the empty array in 'Matched Documents' column in execution_table.
If the 'product_id' field in the main document was missing, what would $lookup do?
AReturn all documents from the foreign collection
BThrow an error and stop aggregation
CReturn an empty array for 'product_details'
DAdd null instead of an array
💡 Hint
Recall that $lookup matches on field values; missing localField means no matches, so empty array is returned.
Concept Snapshot
$lookup syntax:
{
  $lookup: {
    from: <foreign_collection>,
    localField: <field_in_main>,
    foreignField: <field_in_foreign>,
    as: <output_array_field>
  }
}

Behavior:
- For each main doc, find matching foreign docs
- Add matches as array field
- If no matches, array is empty
- Does not modify original docs
Full Transcript
The $lookup stage in MongoDB aggregation joins two collections. It takes each document from the main collection and finds matching documents in a foreign collection based on specified fields. The matches are added as an array field to the original document. Even if only one or no matches are found, the result is always an array. This process does not change the original documents but outputs enriched documents. The execution table shows step-by-step how each document is processed, matches found, and output formed. Key points include understanding that the added field is always an array and that no matches result in an empty array. The visual quiz tests understanding of these steps and outcomes.