MongoDB Indexing

MongoDB supports indexing for efficient execution of queries. Suppose you have to find certain document and you had a collection of documents with no indexes, then you have to scan every document of collection to find a particular document. This is inefficient and take lots of time. So indexes are very important.

Indexes store partial part of the collection's data.


Get Indexes

MongoDB getIndexes() function shows all the indexes available for a collection.

Suppose, we already have a students collection. To get the indexes, run the following query -

db.students.getIndexes();
mongodb insert document

There is already an index for students collection. During creation of collection, MongoDB creates a unique index on the _id field.





Create Index

MongoDB createIndex() function is used to create an index.

db.students.createIndex({name: 1});
mongodb create index

After this, if we run the getIndexes, we will get the following -

mongodb get indexes

Create Unique Index

To create unique index, specify unique on the defined index.

db.students.createIndex({name: 1}, {unique: true});

If we define an index as unique, then building the index fail if the collection already contains duplicate values.





Drop an Index

MongoDB dropIndex() function is used to delete or drop an index.

db.students.dropIndex({'name': 1});
mongodb drop index