📖 Scenario: You are managing a small online bookstore database using MongoDB. The store has many books, and customers often search by title and author. To make searches faster, you want to use indexing.
🎯 Goal: Build a MongoDB collection with book data, add an index on the title field, then add a compound index on author and year fields to speed up queries.
📋 What You'll Learn
Create a MongoDB collection called books with 3 book documents having title, author, and year fields
Create an index on the title field
Create a compound index on author and year fields
Verify the indexes exist in the collection
💡 Why This Matters
🌍 Real World
Online stores and libraries use indexes to quickly find books by title or author without scanning the entire database.
💼 Career
Database administrators and backend developers use indexing to optimize query speed and improve user experience.
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
Hint
Use db.books.insertMany([...]) with the exact documents.
2
Create an index on the title field
Create an index on the title field of the books collection using db.books.createIndex.
MongoDB
Hint
Use db.books.createIndex({ title: 1 }) to create an ascending index on title.
3
Create a compound index on author and year
Create a compound index on the author and year fields of the books collection using db.books.createIndex.
MongoDB
Hint
Use db.books.createIndex({ author: 1, year: 1 }) to create the compound index.
4
Verify the indexes exist in the books collection
Use db.books.getIndexes() to list all indexes on the books collection.
MongoDB
Hint
Use db.books.getIndexes() to see all indexes.
Practice
(1/5)
1. Why is advanced indexing important in MongoDB?
easy
A. It encrypts data for security.
B. It slows down data retrieval to save memory.
C. It deletes duplicate data automatically.
D. It makes data searches faster and more efficient.
Solution
Step 1: Understand the role of indexing
Indexing helps MongoDB find data quickly without scanning the entire collection.
Step 2: Recognize the benefit of advanced indexing