Introduction
MongoDB indexes help improve the speed of queries by allowing MongoDB to find matching documents more efficiently instead of scanning every document in a collection. Indexes can be created on fields such as name, email, or price. In this chapter, you will practice creating, viewing, using, and removing indexes. You will also learn about unique, compound, and text indexes through practical MongoDB commands. MongoDB Indexes Practice questions with solutions to help you understand the concepts.
Q1. Create an Index on the name Field
Problem Statement
Create an ascending index on the name field of the students collection.
MongoDB Command / Query
db.students.createIndex({
name: 1
})
Expected Output
name_1
The value 1 creates an ascending index on the name field.
Q2. View All Indexes
Problem Statement
Display all indexes currently created on the students collection.
MongoDB Command / Query
db.students.getIndexes()
Expected Output
[
{
v: 2,
key: {
_id: 1
},
name: "_id_"
},
{
v: 2,
key: {
name: 1
},
name: "name_1"
}
]
Every MongoDB collection normally has an _id index. The name_1 index is the index created in the previous question.
Q3. Create a Descending Index
Problem Statement
Create a descending index on the age field of the students collection.
MongoDB Command / Query
db.students.createIndex({
age: -1
})
Expected Output
age_-1
The value -1 creates a descending index.
Q4. Create a Unique Index on Email
Problem Statement
Create a unique index on the email field so that two students cannot have the same email address.
MongoDB Command / Query
db.students.createIndex(
{ email: 1 },
{ unique: true }
)
Expected Output
email_1
Now MongoDB will prevent duplicate values in the email field.
For example:
db.students.insertOne({
name: "Aman",
email: "aman@example.com"
})
If another document already has the same email, MongoDB returns a duplicate-key error.
Q5. Create a Compound Index
Problem Statement
Create an index using both course and age fields.
MongoDB Command / Query
db.students.createIndex({
course: 1,
age: 1
})
Expected Output
course_1_age_1
This is called a compound index because it contains multiple fields.
The order of fields in a compound index is important.
Q6. Find Documents Using an Indexed Field
Problem Statement
Find students whose course is Python.
MongoDB Command / Query
db.students.find({
course: "Python"
})
Expected Output
{
_id: ObjectId("..."),
name: "Rahul",
age: 16,
course: "Python"
}
If an appropriate index exists on course, MongoDB may use that index to make the query more efficient.
To inspect the query plan, use:
db.students.find({
course: "Python"
}).explain("executionStats")
The query plan can show whether MongoDB used an index.
Q7. Check Whether a Query Uses an Index
Problem Statement
Use explain() to check the execution plan of a query searching for a student’s email.
MongoDB Command / Query
db.students.find({
email: "aman@example.com"
}).explain("executionStats")
Expected Output
The output contains execution information. When an index is used, the winning plan can contain a stage such as:
{
stage: "IXSCAN"
}
IXSCAN indicates that MongoDB scanned an index.
If MongoDB performs a collection scan instead, the plan can contain:
{
stage: "COLLSCAN"
}
The actual execution plan depends on the collection, indexes, query, and data distribution.
Q8. Create a Text Index for Searching Text
Problem Statement
Create a text index on the description field of a products collection and search for products containing the word laptop.
MongoDB Command / Query
First create the index:
db.products.createIndex({
description: "text"
})
Then search the indexed text:
db.products.find({
$text: {
$search: "laptop"
}
})
Expected Output
{
_id: ObjectId("..."),
name: "Laptop Stand",
description: "Adjustable laptop stand for office use"
}
A text index supports text-search queries using $text.
Q9. Drop a Specific Index
Problem Statement
Remove the name_1 index from the students collection.
MongoDB Command / Query
db.students.dropIndex("name_1")
Expected Output
{
nIndexesWas: 4,
ok: 1
}
The exact nIndexesWas value depends on how many indexes currently exist in your collection.
You can verify the remaining indexes with:
db.students.getIndexes()
Q10. Create and Remove an Index for Product Prices
Problem Statement
Create an ascending index on the price field of the products collection, verify it, and then remove it.
MongoDB Command / Query
Create the index:
db.products.createIndex({
price: 1
})
Check the indexes:
db.products.getIndexes()
Remove the index:
db.products.dropIndex("price_1")
Expected Output
price_1
After removing the index:
{
nIndexesWas: 2,
ok: 1
}
The exact number of indexes depends on the indexes already present in the collection.
Key Takeaways
- An index helps MongoDB find matching documents more efficiently.
createIndex()is used to create an index.1creates an ascending index.-1creates a descending index.getIndexes()displays the indexes of a collection.- A unique index prevents duplicate values for an indexed field.
- A compound index contains multiple fields.
- A text index supports text-search queries using
$text. explain("executionStats")helps inspect how MongoDB executes a query.IXSCANindicates an index scan, whileCOLLSCANindicates a collection scan.dropIndex()removes a specific index.- Indexes can improve read performance, but they also require storage and can add work to insert and update operations.
- The useful indexes for an application depend on its actual query patterns.
FAQs
1. What is an index in MongoDB?
An index is a data structure that MongoDB can use to locate documents more efficiently when processing certain queries.
2. How do you create an index in MongoDB?
Use the createIndex() method.
db.students.createIndex({
name: 1
})
3. How do you see all indexes in MongoDB?
Use getIndexes().
db.students.getIndexes()
4. What is a unique index in MongoDB?
A unique index prevents multiple documents from having the same indexed value.
db.students.createIndex(
{ email: 1 },
{ unique: true }
)
5. What is a compound index?
A compound index is an index containing two or more fields.
db.students.createIndex({
course: 1,
age: 1
})
6. What is the difference between IXSCAN and COLLSCAN?
IXSCAN means MongoDB is scanning an index as part of the query plan. COLLSCAN means MongoDB is scanning the collection’s documents.
7. Can indexes slow down MongoDB?
Yes. Indexes can improve query performance, but they also consume storage and can increase the work required for insert, update, and delete operations because the relevant indexes may need to be maintained.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
