0
0
MongoDBquery~30 mins

Joins vs embedding decision in MongoDB - Hands-On Comparison

Choose your learning style9 modes available
Joins vs Embedding Decision in MongoDB
📖 Scenario: You are building a simple online bookstore database using MongoDB. You need to decide how to organize your data for books and their authors. You want to practice creating collections and deciding when to embed data or reference it (similar to joins).
🎯 Goal: Build two collections: authors and books. Practice embedding author details inside books for quick access, and also practice referencing authors by ID to simulate a join.
📋 What You'll Learn
Create an authors collection with exactly two authors with specified fields.
Create a books collection with three books, embedding author info in one book and referencing author IDs in others.
Use MongoDB insert statements with exact field names and values.
Demonstrate a query that uses $lookup to join books with authors by reference.
💡 Why This Matters
🌍 Real World
Online bookstores and many other applications need to decide between embedding related data or referencing it to balance performance and data consistency.
💼 Career
Understanding when to embed or reference data in MongoDB is a key skill for backend developers and database administrators working with NoSQL databases.
Progress0 / 4 steps
1
Create the authors collection
Create a collection called authors and insert exactly two documents with these fields and values: { _id: 1, name: "Jane Austen", country: "UK" } and { _id: 2, name: "Mark Twain", country: "USA" }.
MongoDB
Need a hint?

Use insertMany on db.authors with an array of two author objects.

2
Create the books collection with embedded author
Create a collection called books and insert one document for the book "Pride and Prejudice" with these fields: { title: "Pride and Prejudice", year: 1813, author: { name: "Jane Austen", country: "UK" } }. Embed the author details inside the book document.
MongoDB
Need a hint?

Use insertOne on db.books with the book document embedding the author object.

3
Insert books referencing authors by ID
Insert two more documents into the books collection for the books "Adventures of Huckleberry Finn" (year 1884) and "Emma" (year 1815). Instead of embedding, reference the authors by their _id using the field author_id with values 2 and 1 respectively.
MongoDB
Need a hint?

Use insertMany on db.books with two book documents referencing authors by author_id.

4
Query books with author details using $lookup
Write an aggregation query on books that uses $lookup to join the authors collection on author_id and _id. The query should add a field author_info with the matching author document.
MongoDB
Need a hint?

Use db.books.aggregate with a $lookup stage specifying from, localField, foreignField, and as.