0
0
MongoDBquery~30 mins

Why document databases over relational in MongoDB - See It in Action

Choose your learning style9 modes available
Why Document Databases Over Relational Databases
📖 Scenario: You are working for a small online bookstore. The store wants to keep track of books, authors, and customer reviews. You need to decide how to store this data efficiently.
🎯 Goal: Build a simple document database structure using MongoDB that shows why document databases can be better than relational databases for this use case.
📋 What You'll Learn
Create a collection called books with embedded author and reviews data
Add a configuration variable maxReviews to limit the number of reviews stored
Write a query to find books with more than maxReviews reviews
Add a final index on the title field to speed up searches
💡 Why This Matters
🌍 Real World
Document databases like MongoDB are great for storing complex data with nested structures, such as books with authors and reviews all in one place. This reduces the need for complex joins and makes data retrieval faster and simpler.
💼 Career
Many modern applications use document databases for flexible and scalable data storage. Knowing how to design and query these databases is valuable for backend developers, data engineers, and database administrators.
Progress0 / 4 steps
1
DATA SETUP: Create the books collection with embedded documents
Create a MongoDB collection called books with these exact documents: one book titled 'Learn MongoDB' by author { name: 'Alice', age: 30 } and two reviews { user: 'Bob', rating: 5 } and { user: 'Carol', rating: 4 } embedded inside the book document.
MongoDB
Need a hint?

Use insertOne to add a document with embedded author and reviews arrays.

2
CONFIGURATION: Add a variable to limit reviews
Create a variable called maxReviews and set it to 1 to limit how many reviews you want to consider for filtering.
MongoDB
Need a hint?

Use const maxReviews = 1 to create the variable.

3
CORE LOGIC: Query books with more than maxReviews reviews
Write a MongoDB query using find to get all books where the number of reviews is greater than maxReviews. Use $expr and $gt operators with $size on the reviews array.
MongoDB
Need a hint?

Use db.books.find({ $expr: { $gt: [ { $size: '$reviews' }, maxReviews ] } }) to filter.

4
COMPLETION: Add an index on the title field
Create an index on the title field in the books collection using createIndex to speed up searches by title.
MongoDB
Need a hint?

Use db.books.createIndex({ title: 1 }) to create the index.