Creating Index on MongoDB Database

Creating Index on MongoDB Database

Instructor-svgAl-Mamun Sarkar
Dec 10 , 2020

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} )

 

  • Share On:
  • fb
  • twitter
  • pinterest
  • instagram