MongoDB Tutorial - MongoDB Indexing

Indexes are data structures that store the indexed fields from a document in an easy to traverse form.

The indexed fields are ordered by the value as specified in index.


To create an index, use ensureIndex() method of mongodb.

The basic syntax of ensureIndex() method is as follows()


key is the to-be-indexed field name and 1 is for ascending order.

To create index in descending order, use -1.

We can pass in multiple fields to ensureIndex() method to create index on multiple fields.





ensureIndex() method accepts options listed as below.

Parameter Type Description
background Boolean true value causes to build the index in the background so that building an index does not block other database activities. The default value is false.
unique Boolean Creates a unique index. true values creates a unique index. The default value is false.
name string The name of the index. If unspecified, MongoDB creates an index name by concatenating the names of the indexed fields and the sort order.
dropDups Boolean Creates a unique index on a field that may have duplicates. MongoDB indexes the first occurrence of a key and removes all documents that contain subsequent duplicated key. Specify true to create unique index. The default value is false.
sparse Boolean true value makes the index only reference documents with the specified field. The default value is false.
expireAfterSeconds integer Specifies a time in seconds to control how long MongoDB retains documents in this collection.
v index version The index version number. The default index version depends on the version of mongod.
weights document The weight is a number between 1 and 99,999 and denotes the significance of the field relative to the other indexed fields in terms of the score.
default_language string For a text index, the language determines the stop words, stemmer and tokenizer. The default value is english.
language_override string For a text index, override the default language.