📖 Scenario: You work at a small online bookstore. You have two collections: books and authors. Each book has an author_id that matches the _id of an author. You want to combine information from both collections to see each book with its author's details.
🎯 Goal: Build a MongoDB aggregation query using $lookup to join the books collection with the authors collection, so each book document includes its author's information.
📋 What You'll Learn
Create a books collection with three books, each having _id, title, and author_id fields.
Create an authors collection with three authors, each having _id and name fields.
Write an aggregation query on books using $lookup to join with authors on author_id and _id.
Add a $project stage to show only title and the joined author name.
💡 Why This Matters
🌍 Real World
Joining collections is common when you have related data in different places, like customers and orders or products and suppliers.
💼 Career
Understanding $lookup is essential for MongoDB developers to combine data efficiently without duplicating it.
Progress0 / 4 steps
1
Create the books collection
Create a books collection with these exact documents: { _id: 1, title: "The Great Gatsby", author_id: 101 }, { _id: 2, title: "1984", author_id: 102 }, and { _id: 3, title: "To Kill a Mockingbird", author_id: 103 }.
MongoDB
Hint
Use db.books.insertMany() with an array of objects for the three books.
2
Create the authors collection
Create an authors collection with these exact documents: { _id: 101, name: "F. Scott Fitzgerald" }, { _id: 102, name: "George Orwell" }, and { _id: 103, name: "Harper Lee" }.
MongoDB
Hint
Use db.authors.insertMany() with an array of author objects.
3
Write the aggregation query with $lookup
Write an aggregation query on books using db.books.aggregate() with a $lookup stage that joins authors on author_id from books matching _id from authors. Use as: "author_info" to store the joined data.
MongoDB
Hint
Use $lookup inside db.books.aggregate() with the correct fields and collection names.
4
Add $project to show book title and author name
Add a $project stage after $lookup in the aggregation pipeline to show only the title field and the first element's name from author_info as author.
MongoDB
Hint
Use $project to keep title and extract the first author's name from author_info array.
Practice
(1/5)
1. What does the $lookup stage do in a MongoDB aggregation pipeline?
easy
A. It deletes documents from a collection.
B. It joins documents from two collections based on a matching field.
C. It sorts documents in ascending order.
D. It updates documents with new values.
Solution
Step 1: Understand the purpose of $lookup
$lookup is used to combine documents from two collections by matching fields.
Step 2: Compare with other options
Deleting, sorting, or updating documents are different operations and not related to $lookup.
Final Answer:
It joins documents from two collections based on a matching field. -> Option B
Quick Check:
$lookup joins collections = A [OK]
Hint: Remember: $lookup is like a join in SQL [OK]
Common Mistakes:
Confusing $lookup with update or delete operations
Thinking $lookup sorts documents
Assuming $lookup modifies documents instead of joining
2. Which of the following is the correct syntax for a basic $lookup stage in MongoDB?
The correct keys are from, localField, foreignField, and as.
Step 2: Check each option
{ $lookup: { from: 'other', localField: 'id', foreignField: 'userId', as: 'joinedData' } } uses all correct keys and syntax. Options A, B, and C have incorrect or missing keys.
Hint: Use keys: from, localField, foreignField, as [OK]
Common Mistakes:
Using wrong key names like collection or joinAs
Omitting the 'as' field for output array
Missing foreignField or localField keys
3. Given two collections: orders with documents { _id: 1, productId: 101 } and products with documents { _id: 101, name: 'Pen' }, what will be the result of this aggregation on orders?
Assuming the users collection uses _id as the user ID field.
medium
A. The 'as' field cannot be 'userDetails'.
B. The localField should be 'id' instead of 'userId'.
C. The 'from' field should be 'user' not 'users'.
D. The foreignField should be '_id' instead of 'id'.
Solution
Step 1: Check foreignField correctness
The users collection uses _id as the ID field, so foreignField must be '_id'.
Step 2: Verify other fields
localField and as are valid; collection name 'users' is correct.
Final Answer:
The foreignField should be '_id' instead of 'id'. -> Option D
Quick Check:
foreignField must match actual field = C [OK]
Hint: Match foreignField to actual field name in other collection [OK]
Common Mistakes:
Using wrong foreignField name
Changing 'as' field unnecessarily
Mistaking collection name pluralization
5. You have two collections: students with { _id: 1, name: 'Alice' } and grades with multiple documents per student like { studentId: 1, score: 85 }. How do you write a $lookup to get each student with all their grades in an array called allGrades?