0
0
MongoDBquery~30 mins

Collections vs tables mental model in MongoDB - Hands-On Comparison

Choose your learning style9 modes available
Collections vs Tables Mental Model in MongoDB
📖 Scenario: You are helping a small bookstore organize its data. The bookstore wants to store information about books and customers. You will create a MongoDB collection to hold book data, similar to how a table holds data in a traditional database.
🎯 Goal: Build a MongoDB collection named books that stores documents representing books with fields for title, author, and year. Then, add a configuration variable to filter books published after a certain year. Finally, write a query to find those books and complete the setup by creating an index on the author field.
📋 What You'll Learn
Create a MongoDB collection named books with 3 book documents
Add a variable year_threshold to filter books published after this year
Write a query to find books with year greater than year_threshold
Create an index on the author field in the books collection
💡 Why This Matters
🌍 Real World
Understanding collections and documents in MongoDB helps you organize data for real applications like bookstores, libraries, or online shops.
💼 Career
Many companies use MongoDB for flexible data storage. Knowing how collections work compared to tables is essential for database roles and backend development.
Progress0 / 4 steps
1
Create the books collection with 3 book documents
Create a MongoDB collection called books and insert exactly these 3 documents: { title: 'The Hobbit', author: 'J.R.R. Tolkien', year: 1937 }, { title: '1984', author: 'George Orwell', year: 1949 }, and { title: 'To Kill a Mockingbird', author: 'Harper Lee', year: 1960 }.
MongoDB
Need a hint?

Use db.books.insertMany([...]) to add multiple documents at once.

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

Use const year_threshold = 1940 to create the variable.

3
Write a query to find books published after year_threshold
Write a MongoDB query using db.books.find() to find all books where the year field is greater than the variable year_threshold.
MongoDB
Need a hint?

Use db.books.find({ year: { $gt: year_threshold } }) to find books published after the threshold year.

4
Create an index on the author field
Create an index on the author field in the books collection using db.books.createIndex().
MongoDB
Need a hint?

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