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.


MongoDB Get Indexes

MongoDB provides getIndexes() function to show all the indexes available for a collection.

Suppose we have the following 'students' collection.

{ "_id" : ObjectId("5b7ddc4f529cbc23546dc4c7"), "name" : "Jorz Rai", "age" : 10, "class" : "5A" }
{ "_id" : ObjectId("5b7ddf10529cbc23546dc4c8"), "name" : "Rana Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4c9"), "name" : "Andy Joya", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4ca"), "name" : "Mary Soi", "age" : 11, "class" : "5C" }
{ "_id" : ObjectId("5b7de0f4529cbc23546dc4cb"), "name" : "Priska Somya", "age" : 12, "class" : "6A" }
mongodb sort

To get the indexes, run the following query -

db.students.getIndexes();
mongodb insert document

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





Create Index

MongoDB provides createIndex() function to create an index.

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

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

mongodb get indexes

Create Unique Index

To create a 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 fails if the collection already contains duplicate values.





Drop an Index

MongoDB provides the dropIndex() function to delete or drop an index.

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




Read more articles


General Knowledge



Learn Popular Language