0
0
MongoDBquery~30 mins

Denormalization trade-offs in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Denormalization Trade-offs in MongoDB
📖 Scenario: You are building a simple online bookstore database using MongoDB. You want to understand how denormalization works by embedding author details directly inside book documents instead of referencing them separately.
🎯 Goal: Create a MongoDB collection with books that embed author information. Then add a configuration variable to control whether to embed or reference authors. Finally, write a query to retrieve books with embedded author details.
📋 What You'll Learn
Create a books collection with embedded author details
Add a variable embedAuthors to control embedding
Write a query to find all books with embedded author names
Add a final step to show how to switch between embedding and referencing
💡 Why This Matters
🌍 Real World
Denormalization by embedding related data is common in MongoDB to improve read performance by reducing the need for joins.
💼 Career
Understanding when to embed or reference data is key for designing efficient NoSQL databases in real-world applications.
Progress0 / 4 steps
1
Create the books collection with embedded authors
Create a MongoDB collection called books with two documents. Each document must have a title field and an embedded author field. The author field should be an object with name and birthYear. Use these exact values: First book: title "The Great Gatsby", author name "F. Scott Fitzgerald", birthYear 1896. Second book: title "1984", author name "George Orwell", birthYear 1903.
MongoDB
Need a hint?

Use db.books.insertMany() with an array of objects. Each object should have title and author fields. The author is an embedded object.

2
Add a variable embedAuthors to control embedding
Create a JavaScript variable called embedAuthors and set it to true. This variable will control if authors are embedded or referenced.
MongoDB
Need a hint?

Use const embedAuthors = true to create the variable.

3
Write a query to find all books with embedded author names
Write a MongoDB query to find all documents in the books collection where the author.name field exists. Use db.books.find() with a filter that checks for author.name.
MongoDB
Need a hint?

Use db.books.find({ "author.name": { $exists: true } }) to find books with embedded author names.

4
Add a final step to show switching between embedding and referencing
Add an if statement that checks if embedAuthors is true. If true, assign the embedded author object to a variable called bookAuthor. Otherwise, assign a reference ID string "authorId123" to bookAuthor.
MongoDB
Need a hint?

Use if (embedAuthors) { bookAuthor = {...} } else { bookAuthor = "authorId123" } to show the trade-off.