Paramclasses Academy - Blog

Tutorials Details

←
Post 19 of 35
→

MongoDB Indexes Explained: Improve Query Performance with Examples

MongoDB Indexes Explained: Improve Query Performance with Examples

November 5, 2026

MongoDB Indexes Explained: Improve Query Performance

Introduction

When a MongoDB collection contains only a few documents, searching for information is usually quick. But as the collection grows to thousands or millions of documents, queries can take more time if MongoDB has to examine many records.

MongoDB indexes help solve this problem.

An index is a special data structure that stores information about selected fields in a collection. It helps MongoDB locate matching documents without scanning every document in the collection.

For example, imagine an online shopping application with one million customer records. If you frequently search customers using their email address, creating an index on the email field can make those searches much more efficient.

In this tutorial, you will learn:

  • What indexes are in MongoDB.

  • Why indexes are important.

  • How MongoDB searches documents without an index.

  • How to create an index using createIndex().

  • How to view and test indexes.

  • What a single-field index is.

  • What a compound index is.

  • How to analyze query performance using explain().

Let's understand MongoDB indexing with practical examples using MongoDB Shell (mongosh).

1. What Is an Index in MongoDB?

An index is a data structure that stores the values of selected fields in an organized way so MongoDB can find documents more efficiently.

Without an appropriate index, MongoDB may need to perform a collection scan, examining documents one by one to find matching results.

With an appropriate index, MongoDB can use the indexed field to locate matching documents more efficiently.

Real-World Example

Suppose a college database contains 100,000 student records.

If you search for a student using their email address without an index, MongoDB may examine many documents.

If an index exists on the email field, MongoDB can use that index to locate the matching record.

Simple comparison:

  • Without an index: Search through many documents.

  • With an index: Use an organized index structure to locate matching records.

Indexes can improve query performance, but they also require storage and add work to write operations because MongoDB must maintain the indexes when data changes.

2. Create a Database and Collection

First, open MongoDB Shell (mongosh) and select a database:

use collegeDB

Create a collection named students and insert sample records:

db.students.insertMany([
    {
        name: "Rahul Sharma",
        email: "rahul@example.com",
        age: 22,
        city: "Raipur"
    },
    {
        name: "Amit Verma",
        email: "amit@example.com",
        age: 24,
        city: "Delhi"
    },
    {
        name: "Priya Singh",
        email: "priya@example.com",
        age: 21,
        city: "Mumbai"
    },
    {
        name: "Neha Patel",
        email: "neha@example.com",
        age: 23,
        city: "Raipur"
    }
])

To display all student records:

db.students.find()

We will use this collection to understand how indexes work.

3. Search Documents Without an Index

Let's search for a student using their city:

db.students.find({
    city: "Raipur"
})

If there is no suitable index for this query, MongoDB may perform a collection scan.

A collection scan is represented by COLLSCAN in the query execution plan.

To inspect the query:

db.students.find({
    city: "Raipur"
}).explain("executionStats")

Look at these important fields in the output:

Field Meaning
stage Execution stage used by the query
nReturned Number of documents returned
totalDocsExamined Number of documents examined
executionTimeMillis Execution time reported by the query

If the winning plan contains COLLSCAN, MongoDB is scanning the collection.

Note: The execution time depends on hardware, data size, cache state and other factors. A small collection may not show a meaningful speed difference.

4. How to Create an Index in MongoDB

MongoDB provides the createIndex() method to create an index on a collection.

Syntax:

db.collectionName.createIndex({
    fieldName: 1
})

Here:

  • 1 means ascending index order.

  • -1 means descending index order.

Example: Create an Index on the City Field

db.students.createIndex({
    city: 1
})

MongoDB creates an ascending index on the city field.

Now run the same query:

db.students.find({
    city: "Raipur"
})

Check the execution plan again:

db.students.find({
    city: "Raipur"
}).explain("executionStats")

If MongoDB selects the new index, the winning plan will commonly contain IXSCAN, which indicates an index scan.

Important: Creating an index does not guarantee that MongoDB will use it for every query. The query planner chooses a plan based on available indexes, query conditions and estimated costs.

5. Types of Indexes in MongoDB

MongoDB supports several index types for different requirements.

Some commonly used index types are:

  1. Single Field Index

  2. Compound Index

  3. Multikey Index

  4. Text Index

  5. Geospatial Index

  6. Hashed Index

  7. Wildcard Index

Let's understand the most commonly used types.

6. Single Field Index

A single-field index is created on one field of a document.

It is useful when your application frequently searches or sorts documents using a particular field.

Example:

db.students.createIndex({
    email: 1
})

This creates an ascending index on the email field.

Search using the indexed field:

db.students.find({
    email: "rahul@example.com"
})

You can also create a descending index:

db.students.createIndex({
    age: -1
})

When to use a single-field index:

  • When frequently searching by one field.

  • When sorting by a commonly used field.

  • When a query pattern repeatedly filters on the same field.

7. Compound Index in MongoDB

A compound index is an index created on two or more fields.

It is useful when queries frequently filter or sort using multiple fields together.

Example:

Suppose you frequently search students by city and age.

Create a compound index:

db.students.createIndex({
    city: 1,
    age: 1
})

Now search using both fields:

db.students.find({
    city: "Raipur",
    age: 22
})

MongoDB can use the compound index for suitable queries.

Important: Field Order Matters

A compound index on:

{
    city: 1,
    age: 1
}

is ordered first by city and then by age.

This index can support queries using:

  • city

  • city and age

It is not generally equivalent to an index on age alone.

Always design compound indexes according to your actual query patterns.

8. How to View All Indexes in MongoDB

MongoDB provides the getIndexes() method to display indexes created on a collection.

Example:

db.students.getIndexes()

This displays the available indexes, including:

  • Index name

  • Indexed fields

  • Index key order

  • Additional index properties

Every standard collection has a default index on the _id field.

9. How to Analyze Query Performance Using explain()

The explain() method helps you understand how MongoDB executes a query.

It is useful for identifying whether a query uses an index or scans the entire collection.

Example:

db.students.find({
    email: "rahul@example.com"
}).explain("executionStats")

Important execution stages include:

Stage Meaning
COLLSCAN MongoDB scans documents in the collection
IXSCAN MongoDB scans an index
FETCH MongoDB retrieves documents after locating index entries

Example: Compare Index Usage

First, inspect a query without a suitable index:

db.students.find({
    city: "Delhi"
}).explain("executionStats")

Now create an index:

db.students.createIndex({
    city: 1
})

Run the same query again:

db.students.find({
    city: "Delhi"
}).explain("executionStats")

Compare the winning plan and execution statistics.

Remember: A query returning very few documents from a tiny collection may still be handled differently by the query planner. Use realistic data and query patterns when evaluating index performance.

10. Unique Index in MongoDB

A unique index ensures that the indexed field or combination of fields does not contain duplicate index keys.

It is useful for fields such as email addresses when each user must have a distinct email.

Example:

db.users.createIndex(
    {
        email: 1
    },
    {
        unique: true
    }
)

Now try inserting two users with the same email:

db.users.insertOne({
    name: "Rahul",
    email: "rahul@example.com"
})
db.users.insertOne({
    name: "Amit",
    email: "rahul@example.com"
})

If the unique index is successfully created, the second insertion fails with a duplicate-key error.

Note: Existing duplicate values must be resolved before creating a unique index. A unique index also has specific behavior for missing and null fields, so plan those cases carefully.

11. When Should You Create Indexes?

Indexes are useful when your application frequently:

  • Searches documents using specific fields.

  • Filters records using common query conditions.

  • Sorts results using frequently accessed fields.

  • Enforces uniqueness.

  • Queries large collections using predictable access patterns.

However, creating indexes on every field is not recommended.

Each additional index consumes storage and increases the work required for inserts, updates and deletes.

Choose indexes based on real application queries rather than creating them without a clear purpose.

12. Best Practices for MongoDB Indexing

Follow these practices to design useful indexes:

  1. Index frequently queried fields: Prioritize fields used regularly in filters and sorts.

  2. Use compound indexes carefully: Consider field order and the queries your application actually runs.

  3. Avoid unnecessary indexes: Too many indexes increase storage requirements and write overhead.

  4. Use unique indexes when appropriate: Prevent duplicate values where uniqueness is a business requirement.

  5. Analyze queries with explain(): Check execution plans and statistics before and after index changes.

  6. Consider write performance: Remember that indexes must be maintained when documents are inserted, updated or deleted.

  7. Test with realistic data: A small sample collection may not represent production query behavior.

  8. Review index usage: Monitor whether existing indexes are useful for your application's workload.

13. Practical Exercises

Try these exercises using MongoDB Shell:

Exercise 1: Create a database named collegeDB and a collection named students.

Exercise 2: Insert at least 20 student documents containing name, email, age and city.

Exercise 3: Create a single-field ascending index on the email field.

Exercise 4: Create a descending index on the age field.

Exercise 5: Create a compound index using city and age.

Exercise 6: Use getIndexes() to display all indexes.

Exercise 7: Run explain("executionStats") on a query that searches by email.

Exercise 8: Create a unique index on a suitable field in a separate collection and test duplicate insertion.

Conclusion

MongoDB indexes are important for improving query efficiency, especially when working with large collections.

In this tutorial, we learned what indexes are, why they are useful, how to create single-field and compound indexes, how to view indexes and how to analyze query execution using explain().

We also explored unique indexes and indexing best practices.

A well-designed indexing strategy helps MongoDB applications handle data efficiently while balancing read performance, write overhead and storage requirements.

In the next tutorial, we will learn how to create, view and delete indexes in MongoDB with practical examples.

Frequently Asked Questions (FAQs)

1. What is an index in MongoDB?

An index is a data structure that helps MongoDB locate documents more efficiently without scanning the entire collection for every query.

2. How do I create an index in MongoDB?

Use the createIndex() method:

db.students.createIndex({
    email: 1
})

3. What is the difference between COLLSCAN and IXSCAN?

COLLSCAN means MongoDB scans documents in a collection, while IXSCAN means MongoDB scans an index.

4. What is a compound index in MongoDB?

A compound index is created on two or more fields in a collection.

5. How do I view indexes in MongoDB?

Use:

db.students.getIndexes()

6. Does MongoDB automatically create an index?

MongoDB automatically creates a unique index on the _id field for standard collections.

7. Can too many indexes affect MongoDB performance?

Yes. Indexes consume storage and add overhead to insert, update and delete operations because MongoDB must maintain them.

8. What is explain() in MongoDB?

The explain() method provides information about the query execution plan and statistics, helping developers analyze query behavior.

Learn MongoDB with practical examples at Param Classes – Learn Today, Grow Tomorrow.

←
Post 19 of 35
→