📖 Scenario: You are managing a MongoDB database for a small online bookstore. To make searching for books faster, you want to use indexes on certain fields.
🎯 Goal: Learn how to create an index on a MongoDB collection and verify that the index is being used by queries.
📋 What You'll Learn
Create a MongoDB collection called books with sample book documents
Create an index on the author field
Run a query filtering by author and verify index usage with explain()
Check the query plan to confirm the index is used
💡 Why This Matters
🌍 Real World
Indexes in databases help speed up searches, just like an index in a book helps you find pages quickly.
💼 Career
Database administrators and backend developers use index creation and verification to optimize application performance.
Progress0 / 4 steps
1
Create the books collection with sample data
Insert three documents into the books collection with these exact fields and values: { 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 an array of objects for the books.
2
Create an index on the author field
Create an ascending index on the author field in the books collection using db.books.createIndex().
MongoDB
Hint
Use db.books.createIndex({ author: 1 }) to create an ascending index on the author field.
3
Run a query filtering by author and use explain()
Write a query to find all books where author is exactly "George Orwell" using db.books.find(). Chain .explain() to this query to get the query plan.
MongoDB
Hint
Use db.books.find({ author: "George Orwell" }).explain() to see the query plan.
4
Verify the index is used in the query plan
Check the query plan output from explain() and add a comment line that includes the phrase "IXSCAN" to indicate the index scan is used.
MongoDB
Hint
Look for IXSCAN in the explain output and add a comment like // The query plan shows an IXSCAN.
Practice
(1/5)
1. What does the IXSCAN stage in MongoDB's explain('executionStats') output indicate?
easy
A. The query is updating documents.
B. The query is scanning all documents without an index.
C. The query is using an index to find documents.
D. The query has a syntax error.
Solution
Step 1: Understand the meaning of IXSCAN
The IXSCAN stage means MongoDB is scanning an index to find matching documents.
Step 2: Compare with other stages
If the query was scanning all documents, it would show a COLLSCAN stage instead.
Final Answer:
The query is using an index to find documents. -> Option C
Quick Check:
IXSCAN = index used [OK]
Hint: Look for IXSCAN in explain output to confirm index use [OK]
Common Mistakes:
Confusing IXSCAN with COLLSCAN
Assuming IXSCAN means a full collection scan
Thinking IXSCAN means query error
2. Which of the following is the correct way to run an explain plan with execution stats for a MongoDB query on collection users?
easy
A. db.users.find({age: 25}).explain()
B. db.users.find({age: 25}).explain('executionStats')
C. db.users.explain('executionStats').find({age: 25})
D. db.users.find().explain('stats')
Solution
Step 1: Recall the correct syntax for explain
The correct syntax is to call explain('executionStats') on the cursor returned by find().
Step 2: Check each option
db.users.find({age: 25}).explain('executionStats') correctly calls find() then explain('executionStats'). db.users.explain('executionStats').find({age: 25}) calls explain before find, which is invalid. db.users.find({age: 25}).explain() calls explain without argument, which defaults to 'queryPlanner' not 'executionStats'. db.users.find().explain('stats') uses wrong argument 'stats'.
Final Answer:
db.users.find({age: 25}).explain('executionStats') -> Option B
Quick Check:
find().explain('executionStats') correct [OK]
Hint: Call explain on the find() cursor with 'executionStats' argument [OK]
Common Mistakes:
Calling explain before find()
Using wrong explain argument
Omitting parentheses on find()
3. Given the index on { username: 1 } exists, what will the explain('executionStats') output stage be for this query?
The query filters on username, and an index on { username: 1 } exists, so MongoDB can use this index.
Step 2: Identify the explain stage for index use
When an index is used, the explain output shows IXSCAN stage indicating index scan.
Final Answer:
IXSCAN -> Option A
Quick Check:
Index on username = IXSCAN [OK]
Hint: If query matches indexed field, expect IXSCAN stage [OK]
Common Mistakes:
Expecting COLLSCAN despite index presence
Confusing FETCH with index scan
Assuming SORT appears without sort query
4. You run db.orders.find({status: 'shipped'}).explain('executionStats') but see COLLSCAN instead of IXSCAN. What is the most likely cause?
medium
A. The query syntax is incorrect.
B. The collection is empty.
C. MongoDB does not support indexes on string fields.
D. There is no index on the status field.
Solution
Step 1: Understand COLLSCAN meaning
COLLSCAN means MongoDB scanned all documents because no suitable index was found.
Step 2: Identify cause for no index use
If the query filters on status but no index exists on that field, MongoDB must scan the whole collection.
Final Answer:
There is no index on the status field. -> Option D
Quick Check:
COLLSCAN = no index on query field [OK]
Hint: COLLSCAN means no index matches query filter [OK]
Common Mistakes:
Assuming syntax error causes COLLSCAN
Believing MongoDB can't index strings
Thinking empty collection causes COLLSCAN
5. You have a compound index on { category: 1, price: -1 }. Which query will use this index efficiently according to explain('executionStats')?
hard
A. db.products.find({category: 'books', price: 20}).sort({price: -1})
B. db.products.find({price: {$lt: 20}})
C. db.products.find({category: 'books'}).sort({price: 1})
D. db.products.find({category: 'books', price: {$lt: 20}})
Solution
Step 1: Understand compound index usage
A compound index on { category: 1, price: -1 } can be used efficiently if the query filters on category first, then optionally on price, and the sort matches the index order.
Step 2: Analyze each query
db.products.find({category: 'books', price: 20}).sort({price: -1}) filters on both category and price with equality and sorts price descending, matching the index order, so it uses the index efficiently. db.products.find({price: {$lt: 20}}) filters only on price, which is the second field, so index is not used efficiently. db.products.find({category: 'books'}).sort({price: 1}) sorts price ascending but index has price descending, so sort won't use index efficiently. db.products.find({category: 'books', price: {$lt: 20}}) filters on both but does not specify sort matching index order, so less efficient than A.
Final Answer:
db.products.find({category: 'books', price: 20}).sort({price: -1}) -> Option A
Quick Check:
Compound index needs prefix field filter and matching sort order [OK]
Hint: Filter on first index field and match sort order to use compound index efficiently [OK]
Common Mistakes:
Filtering only on second index field
Ignoring sort direction in compound index
Assuming any filter uses compound index fully
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.