Introduction
A single field index in MongoDB is an index created on one field of a document. It helps MongoDB efficiently process queries that frequently search, sort, or filter using that field. For example, you can create an index on email, age, name, or price. In this chapter, you will practice creating, checking, using, testing, and removing single field indexes with practical MongoDB commands. MongoDB Single Field Index practice questions with solutions to help you understand the concepts.
Q1. Create a Single Field Index on name
Problem Statement
Create an ascending single field index on the name field of the students collection.
MongoDB Command / Query
db.students.createIndex({
name: 1
})
Expected Output
name_1
The name_1 index is created on the name field.
The value 1 means the index is in ascending order.
Q2. Create a Descending Single Field Index on age
Problem Statement
Create a descending single field index on the age field.
MongoDB Command / Query
db.students.createIndex({
age: -1
})
Expected Output
age_-1
The value -1 creates the index in descending order.
Q3. Check Single Field Indexes
Problem Statement
Display all indexes currently available 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"
},
{
v: 2,
key: {
age: -1
},
name: "age_-1"
}
]
The _id_ index is automatically created by MongoDB. The other indexes are single field indexes created by you.
Q4. Create a Single Field Index on email
Problem Statement
Create an ascending single field index on the email field of the students collection.
MongoDB Command / Query
db.students.createIndex({
email: 1
})
Expected Output
email_1
This index can help queries that search students using the email field.
For example:
db.students.find({
email: "rahul@example.com"
})
Q5. Create a Unique Single Field Index
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 enforce uniqueness for the indexed email values.
For example, if this document already exists:
db.students.insertOne({
name: "Rahul",
email: "rahul@example.com"
})
Trying to insert another document with the same email can produce a duplicate-key error.
Q6. Use a Single Field Index for Sorting
Problem Statement
Create an index on price and sort products by price in ascending order.
MongoDB Command / Query
Create the index:
db.products.createIndex({
price: 1
})
Then sort the products:
db.products.find().sort({
price: 1
})
Expected Output
{
name: "Mouse",
price: 800
}
{
name: "Keyboard",
price: 1500
}
{
name: "Laptop",
price: 55000
}
The price field has a single field index, which can support queries and sorting involving that field.
Q7. Check Whether MongoDB Uses the Single Field Index
Problem Statement
Use explain() to inspect the query plan for a search using the email field.
MongoDB Command / Query
db.students.find({
email: "rahul@example.com"
}).explain("executionStats")
Expected Output
The execution plan may contain:
{
stage: "IXSCAN"
}
IXSCAN indicates that an index scan is being used.
If MongoDB performs a collection scan, the plan may contain:
{
stage: "COLLSCAN"
}
The actual plan depends on the collection data, available indexes, and query.
Q8. Create a Named Single Field Index
Problem Statement
Create a single field index on course and give the index a custom name called course_index.
MongoDB Command / Query
db.students.createIndex(
{
course: 1
},
{
name: "course_index"
}
)
Expected Output
course_index
Giving an index a custom name can make it easier to identify when managing multiple indexes.
You can verify it with:
db.students.getIndexes()
Q9. Remove a Single Field Index
Problem Statement
Remove the course_index from the students collection.
MongoDB Command / Query
db.students.dropIndex("course_index")
Expected Output
{
nIndexesWas: 4,
ok: 1
}
The exact value of nIndexesWas depends on how many indexes existed before the operation.
Verify the remaining indexes:
db.students.getIndexes()
Q10. Create a Single Field Index and Test It with explain()
Problem Statement
Create an index on city and inspect the execution plan for a query that searches students from Delhi.
MongoDB Command / Query
Create the index:
db.students.createIndex({
city: 1
})
Run the query with explain():
db.students.find({
city: "Delhi"
}).explain("executionStats")
Expected Output
The execution plan can contain:
{
stage: "IXSCAN"
}
This indicates that MongoDB used an index scan for the query.
If MongoDB chooses not to use the index, the plan may instead contain COLLSCAN. MongoDB’s query planner chooses an execution plan based on the available indexes and the query.
Key Takeaways
- A single field index is created on one document field.
createIndex()in MongoDB is used to create a single field index.1creates an ascending index.-1creates a descending index in MongoDB.getIndexes()displays the indexes of a collection.- A unique single field index prevents duplicate indexed values.
- A custom index name can make index management easier.
explain("executionStats")can be used to inspect how MongoDB executes a query.IXSCANrepresents an index scan.COLLSCANrepresents a collection scan.dropIndex()removes a specific index in MongoDB.- Indexes can improve read and sort performance, but they consume storage and require maintenance when documents are inserted, updated, or deleted.
FAQs
1. What is a single field index in MongoDB?
A single field index is an index created on one field of a MongoDB document, such as name, email, age, or price.
2. How do you create a single field index in MongoDB?
Use createIndex() with one field.
db.students.createIndex({
name: 1
})
3. What does 1 mean in a MongoDB single field index?
1 creates the index in ascending order.
4. What does -1 mean in a MongoDB index?
-1 creates the index in descending order.
db.students.createIndex({
age: -1
})
5. How do you check single field indexes?
Use the getIndexes() method.
db.students.getIndexes()
6. Can a single field index be unique?
Yes. You can create a unique single field index by using the unique: true option.
db.students.createIndex(
{ email: 1 },
{ unique: true }
)
7. How do you remove a single field index?
Use dropIndex() with the index name.
db.students.dropIndex("name_1")
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
