Creating Index on MongoDB Database

Author: Al-mamun Sarkar Date: 2020-12-10 08:50:02

In this lesson, I will show you how to create an index on MongoDB collections.  I will show how to create a single-column index as well as a compound index.

 

Show the indexes of a collection:

db.employees..getIndexes()

 

Create a single-column Index:

db.employees.createIndex( { "email": 1} )

Use 1 for ascending order and -1 for descending order. 

 

Create a compound index:

db.employees.createIndex( { "name": 1, "email": -1} )

Used 1 for ascending order and -1 for descending order. The above command will create an index where the name will be sorted in ascending order and the email will be sorted in descending order.

 

Drop a single-column Index:

db.employees.dropIndex( { "email": 1} )

 

Drop a compound Index:

db.employees.dropIndex( { "name": 1, "email": -1} )