MongoDB Indexes: Creating, Finding & Dropping Top Index Types

Indexes offer users an efficient method of querying data. If you are querying data that is not indexed the query will need to search through all records in a database to locate data that are compatible with the query.

In MongoDB the ability to query without indexes is known as an ‘a collection scan. A collection scan:

  • The result is various bottlenecks in performance
  • It can significantly slow your app

Fortunately, using indexes solves these two issues. By restricting to the amount of information that could be accessed, you’ll improve its overall efficiency.

In this video tutorial I’ll guide you through the different kinds of indexes. We’ll also demonstrate how to manage and create indexes using MongoDB.

(This post is part our MongoDB Guide. Utilize the menu at the top to navigate. )

What are the indexes used in MongoDB?

Indexes are data structures that are used to store just a portion of the collection’s data in a way that is able to be easily accessed.

In the simplest sense, indexes keep the data of fields that are indexed outside of the collection or table, and track their locations on the disk. The values used in indexes are used to organize the fields that are indexed. This order helps in performing equality matches as well as range-based query operations effectively. In MongoDB the definition of indexes is at the collection level, and the indexes for any field or subfield in the collection documents are available.

In in this article, we’ll utilize the following set of data to show the indexing capabilities of MongoDB.Copy

use students db.createCollection("studentgrades") db.studentgrades.insertMany( [ , , , ,  ] ) db.studentgrades.find(,)


Indexes are created by creating indexes

When you create documents within the collection, MongoDB creates a unique index with the field _id. MongoDB describes this index as Default index _id. This index is not able to be removed out of the collection.

If you are able to query this test dataset you will see the _id field , which is used for the index defaultCopy



Let’s now create an index. To do this you can utilize to use the CreateIndex method with the syntax below:Copy

db..createIndex(, )

When creating an index it is necessary to specify the field that will be indexed as well as the direction in which the keys will be placed (1 or -1) to indicate ascending or ascending or.

Another aspect to remember is the names of the indexes. As a default feature, MongoDB will generate index names by concatenating indexed keys according to the direction of every key in the index by using an underscore as the separator. For example, name:1 will be generated as name_1.

The most effective option is to make use of the name option for defining an index name that is unique for designing an index. Indexes are not able to be changed following their creation. (The only method to change the name of the index would be to remove the index as we will show in the following then create it with the name you want to use.)

Let’s create an index with the name field of the collection of student grades and call it a the student Name Index.Copy

db.studentgrades.createIndex( ,  )


Locating indexes

You can search for all available indexes within an MongoDB collection employing the getIndexes method. This will give all indexes of a particular collection.Copy


Let’s see all the indexes of the studentgrades collection by using the command below:Copy


The result:

The output includes the default index _id as well as the index created by the user students named index.

Indexes are falling

To remove the index of a set employ to use the dropIndex method and specify the name of the index to be deleted.Copy


We should remove the index created by the user using its index’s names the student’s name as shown below.Copy

db.studentgrades.dropIndex("student name index")

The result:

It is also possible to utilize the index field value to assist in getting rid of an index with no specified name:Copy



It is possible to use the dropIndexes command also allows you to delete all indexes except the default index _id.Copy



Common MongoDB index types

MongoDB offers a variety of indexes that are employed according to the requirements of the user. These are some of the more popular types:

  • Single field index
  • Index of compound
  • Index of Multikeys

Single field index

The user-defined indexes rely on only one field from the document in order to build an index with ascending or descending order (1 or 1 or). For a single-field index it is not important to sort the key has no impact since MongoDB is able to traverse an index any direction.Copy


The result:

The index above sorts the information ascending order by using the field for names. You can utilize this sort() method to check the way that data is displayed within the index.Copy



Index of compound

There are many fields that can be used within the MongoDB document for the creation of an index compound. This kind of index utilizes the first field to perform the initial sort , and later sort the other fields by preceding ones.Copy


In the compound index above, MongoDB will:

  • Sort first by the subject field.
  • And, for each subject’s value Sort by the grade.

The index could result in a data structure that is like the following:Copy



Index Multikey

MongoDB can index array fields. If the field is indexed that is the array MongoDB can create indexes for each element within the array. Multikey indexes allow users to search for documents by using the elements contained in the array.

MongoDB automatically creates an index with multiple keys when it comes in contact with an array field , but without having to ask the user to determine the type of multikey.

Let’s make a new data set that contains an array field in order to demonstrate the construction of multikey index.Copy

db.createCollection("studentperformance") db.studentperformance.insertMany( [ , , , ] ) db.studentperformance.find(,).pretty()


Now , let’s make an index in the grade field.Copy



The code above will create an automatic Multikey index within MongoDB. If you search for an item by using an array field (grades), MongoDB will look for the initial part of the array specified by the search() method and will then search for the complete match query.

Let’s take for instance the following search query:Copy

db.studentperformance.find(, )

At first, MongoDB will use the multikey index to search documents that have the grades array which contains only the initial element (80) in any location. In the next step, in those selected documents, only those that have all elements that match will be chosen.

Different MongoDB index types

Apart from the well-known Index types listed above, MongoDB also offers some specific index types specifically designed for certain applications:

  • Geospatial index
  • Test index
  • Hashed index

Geospatial Index

MongoDB offers two kinds of indexes that can increase the performance of queries to databases when dealing with geospatial coordinates:

  • 2D indexes that make use of planar geometry that is intended to be used for coordinate pairs that were previously employed for the MongoDB 2.2 as well as earlier.
  • 2dsphere indexes that make use of Spherical Geometry.


db..createIndex({  : "2dsphere" } )

Text index

This typing index of text lets you search for the content of a string within the collection.Copy

db..createIndex({  * : "text" } )

Hashed index

MongoDB Hashed Index type is used to the ability to support hash-based Sharding capability. This will be used to index the value of the hash of the field.Copy

db..createIndex({  * : "hashed" } )

MongoDB index properties

It is possible to enhance the performance of an index by using index properties. This section will help you’ll learn about these common index properties:

  • Index of Sparse
  • Index partial
  • Unique index

Index of Sparse

It is the MongoDB sparse property permits indexes to exclude indexing documents within a collection in the event that the field indexed is not available within a document. This allows the creation of an index that only contains documents that have the field that has been indexed.Copy


The result:

In the earlier students’ grades collection when you create an index with notes field it will only index two documents because the notes field appears just in two files.

Index partial

The partial index function lets users create indexes that are compatible with the specified filtering condition. Partial indexes use the partialFilterExpression option to specify the filter condition.Copy

db.studentgrades.createIndex( ,  )

The result:

The above code will generate an index of the field name however it will only contain documents where the the field score is higher than or equal to.

Unique index

The unique property allows users to create an MongoDB index that contains only unique values. This can:

  • Do not accept duplicate values in the index field
  • The index should be limited to those documents that contain unique values




The above-created index will restrict the indexing of documents that have unique names within the field named name.

Indexes recap

This concludes the MongoDB Indexes Tutorial. You have learned how to make indexes, locate and drop indexes, make use of various types of indexes, and also create complicated indexes. These indexes are then utilized to enhance the capabilities of MongoDB databases, thereby increasing the performance of applications that employ database queries that are fast.

Leave a Reply

Your email address will not be published. Required fields are marked *