0
0
MongoDBquery~30 mins

$lookup for joining collections in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
$lookup for joining collections
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use $project to keep title and extract the first author's name from author_info array.