0
0
MongoDBquery~30 mins

Why document design matters in MongoDB - See It in Action

Choose your learning style9 modes available
Why Document Design Matters in MongoDB
📖 Scenario: You are working for a small online bookstore. You want to store information about books and their authors in a MongoDB database. Good document design will help you store and retrieve data efficiently.
🎯 Goal: Build a MongoDB collection with well-designed documents that store book titles, authors, and publication years. Learn how to structure documents for easy querying and updating.
📋 What You'll Learn
Create a collection called books with documents containing title, author, and year fields.
Add a configuration variable maxYear to filter books published after this year.
Write a query to find all books published after maxYear.
Add an index on the year field to improve query performance.
💡 Why This Matters
🌍 Real World
Good document design helps online stores and apps store and retrieve data quickly and clearly.
💼 Career
Database developers and data engineers must design documents and indexes to optimize performance and maintainability.
Progress0 / 4 steps
1
Create the books collection with initial documents
Create a MongoDB collection called books and insert these exact documents: { title: "The Great Gatsby", author: "F. Scott Fitzgerald", year: 1925 }, { title: "1984", author: "George Orwell", year: 1949 }, and { title: "To Kill a Mockingbird", author: "Harper Lee", year: 1960 }.
MongoDB
Need a hint?

Use insertMany to add multiple documents to the books collection.

2
Add a configuration variable maxYear
Create a variable called maxYear and set it to 1930. This will be used to filter books published after this year.
MongoDB
Need a hint?

Use const maxYear = 1930 to create the variable.

3
Query books published after maxYear
Write a MongoDB query using find on the books collection to get all documents where the year field is greater than maxYear. Store the query in a variable called recentBooks.
MongoDB
Need a hint?

Use db.books.find({ year: { $gt: maxYear } }) to get books published after maxYear.

4
Add an index on the year field
Create an index on the year field of the books collection using createIndex to improve query speed.
MongoDB
Need a hint?

Use db.books.createIndex({ year: 1 }) to create an ascending index on the year field.