MongoDB is a highly flexible, scalable, and distributed NoSQL database used for high volume data storage. MongoDB uses documents and collections instead of rows and tables to construct traditional relational databases. This article deals with indexing in MongoDB, how to create a MongoDB index, its syntax, and output.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What Is Indexing in MongoDB?

The MongoDB index is a special data structure on which the index is created to hold the data of specific fields of documents. It stores a small portion of the data set that can be easily traversed later. A MongoDB index supports the efficient resolution of queries by storing the value of a specific field, ordered by the field's value as specified by the index. 

In the absence of indexing in MongoDB, there is a need to scan every collection document to select those that match the query statement. This scan requires MongoDB to process a large volume of data and is highly inefficient. Moreover, having too many indexes in MongoDB can negatively affect the performance of multiple operations, such as update, insert and delete. That is because indexes use the additional data space and additional write. 

How to Create MongoDB Index

The createIndex() Method 

Syntax: 

>db.COLLECTION_NAME.createIndex({KEY:1})

In the above syntax, the key is the field name that must be created. 1 is used for the ascending order, and to create a descending order index, use -1. 

Example: 

To have a collection of ‘studentdata’, the following fields are present inside the collection: 

student_name, student_id and student_age 

To create the index on student_name field in ascending order:

db.studentdata.createIndex({student_name: 1})

Output: 

MongoDB_Index_1

Following is the list of options that the above method accepts:

Parameter 

Type 

Description 

sparse

Boolean 

The index only references documents with the specified field if true. It uses less space; it behaves differently in sorts. False is the default value. 

name

string

MongoDB generates an index name by concatenating the indexed fields’ names and the sort order if unspecified. 

unique

Boolean 

False is the default value. Creates a unique collection so that the collection does not accept document insertion where the index key or keys match an existing value in the index. Specify true to create a unique index. 

expireAfterSeconds

integer

Specifies a value as a TTL to control how long MongoDB retains documents in this collection. The value is in seconds. 

background

Boolean 

False is the default value. It builds the index in the background so that it doesn’t block other database activities. Specify true to build in the background. 

weights

document

It denotes the significance of the field relative to the other indexed fields in terms of score. The weight is a number ranging from 1 to 99,999. 

default_language

string

English is the default value. The language that determines the list of stop words and the rules for the stemmer and tokenizer for a text index. 

language_override

string

Language is the default value. For a text index, specify the field name in the document that contains the language to override the default language. 

The dropIndex() Method 

The dropIndex() method is used to drop a particular index. 

Syntax

>db.COLLECTION_NAME.dropIndex({KEY:1})

In this, the key is the file name on which the removal of an existing index has to be done. Alternatively, one can specify the index’s name directly as:

dropIndex("name_of_the_index")

Example:

To drop the index created on the student_name field in the collection ‘studentdata’, the following command is to be used:

db.studentdata.dropIndex({student_name: 1})

Output:

MongoDB_Index_2

The dropIndexes() Method 

To drop all the indexes of a collection, the dropIndexes() method is used. 

Syntax:

db.collection_name.dropIndexes()

Example:

To drop all the indexes of ‘studentdata’ collection: 

db.studentdata.dropIndexes()

Output:

MongoDB_Index_3.

Conclusion

Are you looking to acquire skills to collect, manage and analyze data, trends, and types to deliver the best results? Then it’s time to get registered for the Professional Certificate Program in Data Science offered by Simplilearn. Data Science is one of the fastest-growing fields. After completing the course, anyone will become more hireable in any part of the competitive world. With the advanced knowledge and skills, the aspirants can receive a good salary at the entry level. Since the demand for data scientists will increase in the future, the salary hike is likely to increase by 10%. So, acquire new-age skills that will help you tackle business problems by registering for the course straight away.