MongoDB Indexing - MongoDB

What is MongoDB Indexing?

Indexes support efficient resolution of queries and without indexes, MongoDB should scan each document of a collection for selecting those documents which match the query statement. This scan is highly incompetent and needs MongoDB to process a large volume of data.

Indexes are special data structures which store a small portion of the data set in an easy-to-traverse form. Index stores the value of a specific field or set of fields, ordered by the value of the field as mentioned in the index.

ensureIndex() Method

EnsureIndex() method of MongoDB is used for creating an index.


Basic syntax of ensureIndex() method is as follows().

Here key is the name of the field on which index is created and 1 is for ascending order. For creating an index in descending order, use -1.


Multiple fields can be passed in ensureIndex() method, to create index on multiple fields.

ensureIndex() method also accepts list of options (which are optional). Below is the list






This will build an index in the background so that building an index will not block other database activities. Default value isfalse but you can Specify true to build in the background.



This will create a unique index so that the collection does not accept insertion of documents where the index key or keys match an existing value in the index. Default value isfalse but you can Specify true to create a unique index.



It is the name of the index. If unspecified, MongoDB will generate an index name by concatenating the names of the indexed fields and the sort order.



This will create a unique index on a field which may have duplicates. MongoDB indexes only the first occurrence of a key and removes all documents from the collection which contain subsequent occurrences of that key. Default value isfalse but you can Specify true to create a unique index.



If this is true, index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). Default value isfalse.



This will specify a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection.


index version

The index version number and the default index version depends on the version of MongoDB running while creating the index.



Weight is a number ranging from 1 to 99,999 and signifies the importance of the field relative to the other indexed fields in terms of the score.



For a text index, language which determines the list of stop words and the rules for the stemmer and tokenizer. Default value isenglish.



For a text index, specify the name of the field in the document which contains the language to override the default language. Default value is language.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

MongoDB Topics