An index in MongoDB is a data structure that helps the database find documents more efficiently. Without a suitable index, MongoDB may need to scan many documents to find matching records. Indexes can improve query performance when they match the queries your application runs.
Imagine a book containing hundreds of pages. If there is no index, you may need to search page by page to find a topic. A book index helps you locate the topic quickly.
MongoDB indexes work in a similar way. They help MongoDB locate documents using indexed field values.
{
_id: 1,
name: "Rahul",
age: 20,
course: "Java"
}
{
_id: 2,
name: "Priya",
age: 22,
course: "Python"
}
{
_id: 3,
name: "Aman",
age: 19,
course: "Java"
}
If an application frequently searches for students
by name, creating an index on the name
field may improve those queries.
Indexes also have costs. They consume storage and require maintenance when indexed data changes. Too many unnecessary indexes can slow down writes.
MongoDB automatically creates a unique index on the
_id field for a standard collection.
This ensures that two documents in the same collection
cannot have the same _id value.
db.students.find({
_id: 1
})
MongoDB can use the default _id index
to locate a document by its ID.
db.students.getIndexes()
This displays the indexes defined on the
students collection, including the
default _id index.
A single-field index is an index on one field.
Use createIndex() to create it.
db.collection.createIndex({
field: 1
})
Use 1 for ascending index order and
-1 for descending index order.
db.students.createIndex({
name: 1
})
This creates an ascending index on the
name field.
db.students.find({
name: "Rahul"
})
MongoDB may use the index for this query if the query planner determines that it is beneficial.
A descending index stores index keys in descending order.
db.students.createIndex({
age: -1
})
This creates a descending index on the
age field.
db.students.find().sort({
age: -1
})
MongoDB may use the index to support this sort. Whether it does so depends on the query and available indexes.
A compound index contains multiple fields. The order of its fields matters because it affects which queries and sorts the index can support.
db.students.createIndex({
course: 1,
age: -1
})
This creates an index on course in
ascending order, followed by age
in descending order.
db.students.find({
course: "Java"
}).sort({
age: -1
})
This query matches the leading index field and sorts by the second field. The compound index may support both operations.
Compound indexes are particularly useful when their field order matches common query patterns.
A unique index prevents duplicate indexed values from being stored, subject to the index's rules.
db.students.createIndex(
{ email: 1 },
{ unique: true }
)
This creates a unique index on the
email field.
Two documents cannot have the same indexed email value. Before creating a unique index, check existing data for duplicates and consider how missing or null values should be handled.
db.students.insertOne({
name: "Rahul",
email: "rahul@example.com"
})
Inserting another document with the same email will fail if the unique index is active.
Use getIndexes() to inspect the
indexes on a collection.
db.students.getIndexes()
The result includes index names, indexed fields, index directions, and applicable options.
db.students.createIndex({
course: 1
})
db.students.getIndexes()
The output should include the new course index, provided the creation succeeded.
If an index is no longer useful, you can remove it
using dropIndex().
db.students.dropIndex("name_1")
The default index name for
{ name: 1 } is commonly
name_1, unless a custom name was specified.
db.students.dropIndexes()
This removes the collection's non-ID indexes.
MongoDB does not allow you to drop the required
default _id index.
The explain() method helps you inspect
how MongoDB plans and executes a query.
db.students.find({
name: "Rahul"
}).explain("executionStats")
The output includes execution details such as the winning plan, documents examined, and keys examined.
IXSCAN generally indicates an index scan.COLLSCAN indicates a collection scan.totalDocsExamined shows how many documents were examined.totalKeysExamined shows how many index keys were examined.A collection scan is not always a problem. For small collections or queries that return many documents, using an index may not be more efficient.
explain("executionStats") to investigate query performance.
Create a collection named
practice_indexes and insert these documents:
db.practice_indexes.insertMany([
{
_id: 1,
name: "Rahul",
age: 22,
course: "Java",
email: "rahul@example.com"
},
{
_id: 2,
name: "Priya",
age: 19,
course: "Python",
email: "priya@example.com"
},
{
_id: 3,
name: "Aman",
age: 21,
course: "Java",
email: "aman@example.com"
},
{
_id: 4,
name: "Neha",
age: 20,
course: "HTML",
email: "neha@example.com"
}
])
name.age.course and age.email.explain("executionStats").dropIndex().Run the insertion command only once, or clear the test collection before inserting the same sample data again.
1. Which method creates an index?
2. Which index prevents duplicate indexed values?
3. Which method helps inspect a query execution plan?