0
0
MongoDBquery~30 mins

Compound index and field order in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Creating and Using Compound Indexes in MongoDB
📖 Scenario: You are managing a MongoDB database for a small online bookstore. You want to speed up searches that look for books by both author and year of publication.
🎯 Goal: Build a compound index on the author and year fields in the books collection to improve query performance.
📋 What You'll Learn
Create a books collection with sample documents
Define a compound index on author and year fields
Understand the importance of field order in compound indexes
Query the collection using the compound index
💡 Why This Matters
🌍 Real World
Compound indexes help speed up searches that filter on multiple fields, common in real-world apps like bookstores, social media, and e-commerce.
💼 Career
Understanding compound indexes is essential for database administrators and backend developers to optimize query performance and resource usage.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a collection called books and insert these exact documents: { title: "Book A", author: "Alice", year: 2020 }, { title: "Book B", author: "Bob", year: 2019 }, and { title: "Book C", author: "Alice", year: 2018 }.
MongoDB
Need a hint?

Use db.books.insertMany() with an array of documents.

2
Define a compound index on author and year
Create a compound index on the books collection with author as the first field and year as the second field, both in ascending order.
MongoDB
Need a hint?

Use db.books.createIndex() with an object specifying author: 1 and year: 1.

3
Query using the compound index
Write a query to find all books where author is "Alice" and year is greater than or equal to 2019.
MongoDB
Need a hint?

Use db.books.find() with a query object specifying author: "Alice" and year: { $gte: 2019 }.

4
Create a compound index with reversed field order
Create another compound index on the books collection with year as the first field and author as the second field, both in ascending order.
MongoDB
Need a hint?

Use db.books.createIndex() with { year: 1, author: 1 }.