Paramclasses Academy - Blog

Tutorials Details

←
Post 20 of 35
→

How to Create, View and Delete Indexes in MongoDB

How to Create, View and Delete Indexes in MongoDB

November 5, 2026

How to Create, View and Delete Indexes in MongoDB

Introduction

Indexes are an important feature of MongoDB that help improve query performance by allowing MongoDB to find documents more efficiently.

Without indexes, MongoDB may need to scan every document in a collection to find matching records. This operation is called a Collection Scan (COLLSCAN).

With suitable indexes, MongoDB can use an Index Scan (IXSCAN) to locate matching documents more efficiently.

In this tutorial, you will learn how to create, view, and delete indexes in MongoDB using practical examples in MongoDB Shell (mongosh).

1. What Is an Index in MongoDB?

An index is a special data structure that stores information about the values of selected fields in a collection.

It helps MongoDB locate documents without checking every document individually.

Example:

Imagine a students collection containing thousands of student records. If you frequently search students by their email address, creating an index on the email field can help MongoDB find matching records more efficiently.

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

Here:

  • students is the collection name.

  • createIndex() is the method used to create an index.

  • email is the field on which the index is created.

  • 1 represents ascending index order.

2. Create a Database and Collection

Before creating indexes, let's create a sample database and collection.

Open MongoDB Shell (mongosh) and execute:

use collegeDB

Create a students collection:

db.createCollection("students")

Insert sample documents:

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

Verify the inserted documents:

db.students.find()

Now we have a sample collection to practice index operations.

3. How to Create an Index in MongoDB

MongoDB provides the createIndex() method to create an index on one or more fields.

Syntax:

db.collection.createIndex({ field: 1 })

The index order can be:

  • 1 – Ascending order

  • -1 – Descending order

Example: Create an index on the city field

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

MongoDB creates an ascending index on the city field.

You can also create a descending index:

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

This creates an index on the age field in descending order.

4. Create an Index with a Custom Name

MongoDB automatically generates an index name based on the indexed field and its direction.

For example:

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

The default index name will be:

email_1

You can also provide a custom index name using the name option.

db.students.createIndex(
  { email: 1 },
  { name: "student_email_index" }
)

Here, student_email_index is the custom name of the index.

Custom names make indexes easier to identify and manage.

5. How to Create a Compound Index

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

It can be useful when your queries frequently filter or sort using multiple fields.

Example:

Suppose you frequently search students by city and age.

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

This creates a compound index on:

  • city in ascending order.

  • age in descending order.

The order of fields in a compound index is important. MongoDB can efficiently use a compound index for queries that include the first indexed field or an appropriate prefix of the indexed fields.

Example query:

db.students.find({
  city: "Raipur"
}).sort({
  age: -1
})

This query can make use of the compound index shown above.

6. How to Create a Unique Index

A unique index prevents duplicate values in the indexed field.

For example, student email addresses should generally be unique.

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

Now MongoDB will not allow duplicate email values in this collection.

Example:

db.students.insertOne({
  name: "Karan",
  email: "rahul@gmail.com",
  city: "Raipur",
  age: 24
})

If rahul@gmail.com already exists, MongoDB rejects this insert because the unique constraint is violated.

Important: Creating a unique index will fail if existing documents already contain duplicate values for the indexed field. Check and resolve duplicates before creating it.

7. How to View All Indexes in MongoDB

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

Syntax:

db.collection.getIndexes()

Example:

db.students.getIndexes()

This command displays the indexes available on the students collection.

You may see output similar to:

[
  {
    v: 2,
    key: { _id: 1 },
    name: "_id_"
  },
  {
    v: 2,
    key: { city: 1 },
    name: "city_1"
  },
  {
    v: 2,
    key: { email: 1 },
    name: "email_1"
  }
]

The exact output depends on the indexes you have created and your MongoDB version.

Understanding the output:

Field Meaning
key Field and index direction
name Name of the index
v Index version

MongoDB automatically creates an index on the _id field for every standard collection.

8. How to Delete an Index in MongoDB

Sometimes an index is no longer needed. MongoDB provides the dropIndex() method to remove a specific index.

Syntax:

db.collection.dropIndex("index_name")

Example:

First, check the available indexes:

db.students.getIndexes()

Suppose you want to delete the city index.

db.students.dropIndex("city_1")

MongoDB removes the index named city_1.

You can verify the remaining indexes:

db.students.getIndexes()

The deleted index should no longer appear in the list.

9. Delete All Non-_id Indexes

MongoDB also provides the dropIndexes() method to remove all indexes from a collection except the mandatory _id index.

Command:

db.students.dropIndexes()

This removes all non-_id indexes from the students collection.

Important:

  • The _id index is not removed by dropIndexes().

  • This operation can affect query performance.

  • Use it carefully, especially in production databases.

10. How to Check Whether MongoDB Uses an Index

Creating an index does not automatically mean every query will use it.

You can inspect query execution using explain("executionStats").

Example:

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

Look for the winning plan in the output.

Two important execution stages are:

Stage Meaning
IXSCAN MongoDB uses an index scan
COLLSCAN MongoDB scans the collection

An appropriate index may help MongoDB avoid scanning every document.

However, the query planner decides which plan is suitable based on the query, available indexes, and data distribution.

11. Important MongoDB Index Commands

Command Purpose
createIndex() Creates an index
getIndexes() Displays collection indexes
dropIndex() Deletes a specific index
dropIndexes() Deletes all non-_id indexes
explain() Examines query execution

12. Best Practices for Managing MongoDB Indexes

Follow these practices when working with indexes:

  1. Create indexes on fields that are frequently used in queries.

  2. Use compound indexes when queries commonly filter or sort on multiple fields.

  3. Use unique indexes when duplicate values must be prevented.

  4. Review existing indexes using getIndexes().

  5. Remove unused indexes carefully.

  6. Use explain("executionStats") to understand query performance.

  7. Avoid creating unnecessary indexes because indexes consume storage and add overhead to insert, update, and delete operations.

  8. Never attempt to remove the mandatory _id index.

13. Practical Exercise

Try the following tasks in MongoDB Shell:

Task 1: Create a database named companyDB.

Task 2: Create a collection named employees.

Task 3: Insert employee records containing name, email, department, and salary.

Task 4: Create an ascending index on the department field.

Task 5: Create a unique index on the email field. Ensure there are no duplicate email values.

Task 6: Display all indexes using getIndexes().

Task 7: Create a compound index on department and salary.

Task 8: Delete the department index using dropIndex().

Task 9: Verify the remaining indexes.

Task 10: Use explain("executionStats") to inspect a query.

14. Frequently Asked Questions (FAQs)

Q1. What is createIndex() in MongoDB?

createIndex() is a MongoDB method used to create an index on one or more fields in a collection.

Q2. How can I see all indexes in MongoDB?

Use the following command:

db.collection.getIndexes()

Q3. How do I delete a specific index in MongoDB?

Use dropIndex() with the index name:

db.students.dropIndex("city_1")

Q4. What is the difference between dropIndex() and dropIndexes()?

dropIndex() removes a specific index, while dropIndexes() removes all non-_id indexes from a collection.

Q5. Can we delete the _id index in MongoDB?

No. MongoDB maintains the _id index, and it cannot be removed using the normal index deletion methods.

Q6. Does creating more indexes always improve performance?

No. Indexes can improve suitable read queries, but they also consume storage and add overhead to write operations.

Q7. What is the default index name in MongoDB?

MongoDB generally generates an index name using the indexed field and its direction. For example, an ascending index on city is named city_1.

Conclusion

MongoDB indexes help improve query performance by allowing the database to locate matching documents more efficiently.

In this tutorial, we learned how to create indexes using createIndex(), view existing indexes using getIndexes(), and remove indexes using dropIndex() and dropIndexes().

We also explored compound indexes, unique indexes, and query execution analysis using explain("executionStats").

Understanding index management is an important skill for building efficient and scalable MongoDB applications.

Keep practicing these commands in mongosh to strengthen your MongoDB database skills.

←
Post 20 of 35
→