• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:12 mins read

An index is a data structure that helps MongoDB discover documents quickly when performing query with criteria on fields and accelerates data retrieval operations on a collection. In the article, we have discussed what is index and MongoDB operations like creating an index, retrieving index fields, and dropping an index.

Advertisements

In order to explain MongoDB Indexes, first let’s create a collection with some documents.


# Create Collection
db.student.insertMany([
      {  
         _id: 1,
         name: "Charlie",
         age: 24,
         gender: "Male",
         email: "[email protected]",
         marks: 99,
         grade: "A",
         course: {"course1": "Python", "course2": "MongoDB"},
         remarks: ["Excellent student", "Keep it up"]
 
      },
      {
         _id: 2,
         name: "Elena",
         age: 20,
         gender: "Female",
         email: "[email protected]",
         marks: 89,
         grade: "B",
         course: {"course1": "Java", "course2": "MongoDB"},
         remarks: ["Good student", "Keep going"]
      },
      {
         _id: 3,
         name: "Caroline",
         age: 25,
         gender: "Female",
         email: "[email protected]",
         marks: 78,
         grade: "C",
         course: {"course1": "C++", "course2": "CSharp"},
         remarks: ["Hard working student", "Do more better"]
      }
   ]
)

1. What is Index and why do we need it in MongoDB?

When you don’t have an index on a collection, any query on MongoDB performs a table scan resulting query running for a longer time. Indexes help the efficient execution of queries. One can create an index on a single field or multiple fields. Typically choose the fields that are used in query for indexes.

2. Create an index in MongoDB

The index is created in MongoDB via the createIndex() method. There, we provide various ways to create an index of the specific field. 

2.1 Index a single field in MongoDB

Initially, we used the createIndex() method to create the index on the single field of the given MongoDB collection. The below query creates an index on the name field of the student collection in MongoDB. The createIndex() method specifically inputs the field name with index value as an argument. The index is created in ascending order as it is specified with a value of 1.


# create the index on the single field
db.student.createIndex({"name":1})

The following result generates the index of the specified field below.

Index in MongoDB

2.2 Index multiple fields in MongoDB

However, we can use the createIndex() method to create the index on more than one field of the collection.  The createIndex() method can take more than one field at a time to create the index. The query here creates a compound index on the fields age and grade of the student collection in MongoDB. These fields are specified as the argument of the createIndex() method. The age field is indexed in ascending order as set with the value 1, and the grade field is indexed in descending order as it is assigned with a value of -1.


# create the index on more than one field
db.student.createIndex(
              {"age":1,
              "grade":-1})

The following resultant indexes can be seen in the output screen.

Index in MongoDB

2.3 Index a field with a unique argument in MongoDB

The query generates an index on the name field of the student collection by calling the createIndex() method. Here, the createIndex() method also takes the unique parameter with the true value, indicating that there cannot be two documents with the same value for the name field.


# Index a field with a unique argument
db.student.createIndex( { "name": 1 }, { "unique": true } )

Hence, the following expected output is retrieved from the execution of the above query.

Index in MongoDB

2.4 Index a field with a collation argument in MongoDB

The query of MongoDB defines an index on the remarks field of the student collection, with a specific collation option. The createIndex() method is used over the field remarks to index it. Then, the collation option is specified and set with the expression { locale: "en" }, which indicates that the index will use the “en” (English) collation when comparing string values.


# Index a field with a collation argument
db.student.createIndex(
    { remarks: 1 },
    { collation: { locale: "en" } }
)

Thus, the remarks field is the index of the collection student which is ensured by the following output.

Index in MongoDB

2.5 Index an embedded field in MongoDB

The query invoked the createIndex() method, which inputs the first argument course.course1 field to be indexed. Here, the course.course1 refers to a subfield within the course field. So the course1 subfield will be the index of the collection.


# Index an embedded field
db.student.createIndex( { "course.course1": 1 } )

The output yielded indicates that the course.course1 field is now the index as shown in the following image.

Index in MongoDB

3. Get an index field in MongoDB

The getIndexes() method is used to retrieve information about indexes in MongoDB. When called on a collection, it will return a cursor that can be used to iterate through the list of indexes on that collection. The getIndex() method below returns a list of all indexes on the student collection as it is called with no parameter. It will return a document that includes information about each index


#Usage of getIndexes() method
db.student.getIndexes()

The output gives the name of the index, the collection it is on, the fields it indexes, and the options that are used when creating the index below.

Index in MongoDB

4. Drop an index field in MongoDB

In some cases, we need the dropIndex() method to drop the index in MongoDB. This is effective when we want to remove all non-essential indexes from a collection for performance reasons or to free up disk space.

4.1 Drop a single index field in MongoDB

The dropIndex() method below takes the argument, which indicates that the index on the name field should be dropped. The value of 1 indicates the direction of the index (ascending).


# Drop a single index field
db.student.dropIndexes({name:1})

The index has dropped, as shown in the following output.

Index in MongoDB

4.2 Drop all the index fields in MongoDB

Conversely, if we want to drop all the indexes of the collection, then we can call the dropIndex() method with no arguments. The query here removes indexes from a collection in MongoDB by deploying the dropIndex() method. As the method is called with no arguments, it will drop all user-defined indexes on the collection except for the default index on the _id field. 


# drop all the indexes of the collection
db.student.dropIndexes()

The output of the dropIndex() method is yielded in the following image.

Index in MongoDB

5. Conclusion

In conclusion, we came to know that indexes are an essential tool for optimizing query performance in MongoDB. However, creating too many indexes or indexes on large fields can negatively impact performance.

More details about this topic can be found here.