Role of Indexes in MongoDB

Indexes provide high performance read operations for frequently used queries. It includes indexes in MongoDB, describes the types and configuration options for indexes, and describes special types of indexing MongoDB supports. The section also provides tutorials detailing procedures and operational concerns, and providing information on how applications may use indexes.

Basically the indexes in MongoDB are similar to the indexes in other databases. These indexes are defined at the collection level and consists of indexes for many other fields and sub-fields in the documents. Indexing is used to limit the number of documents to be viewed to fasten the operations.

Consider following examples –

Types of Indexes in MongoDB

There are fundamentally six types of indexes supported by MongoDB –

Default _id : This is the default and unique index that exists in every collection. If there are no values assigned to the index, MongoDB creates an _id field with an ObjectId value.

Single Field : MongoDB supports user-defined indexes on a single field.

For example, db.userdetails.find().sort({“education”:1})

It is clear from the above example that the field education is sorting in the ascending order.

Compound Index : Not only single field but MongoDB supports user-defined indexes on multiple fields. The sequence of fields inside the compound index denotes certain order.

For example, in following example education will be sorted at first and then the password.

db.userdetails.find().sort({"education":1,"password":-1})

Multikey Index : MongoDB supports multikey indexes for the data stored in arrays. Each column index holds an array value and separate index values for the individual entries. This helps in matching the elements of the array.

Consider following example of a document within a collection where extra is an array, ‘friends’ and ‘ban_firends_id’ are the sub-arrays.