Indexes support more efficient query resolution. Without an index, MongoDB must scan through every Document of a Collection to select the Documents that are associated with the query. This scan can be inefficient and requires MongoDB to process a large amount of data.
Indexes are special data structures that hold a small part of the data set, making it easier to "play" with the Collection. The index stores the value of a particular field or set of fields, sorted by the value of the field as defined in the index.
ensureIndex() method in MongoDB
To create an index, you need to use the ensureIndex() method of MongoDB.
The basic syntax of the ensureIndex() method is as follows:
Here, key is the name of the field you want to index and 1 is for ascending order. To create an index in descending order you need to use -1.
In the ensureIndex() method you can pass multiple fields, to create an index on multiple fields you use:
The ensureIndex() method also accepts an arbitrary list of options, listed below:
Parameters Type Describe
background Boolean Build the index in the background so that it doesn't interfere with other database operations. Specify true to build in Background. Default value is false
unique Boolean Create a unique index so that the Collection will not accept the insertion of Documents whose key is associated with an existing value in the index. Set to true to create a unique index. Default value is false
name Chain The name of the index. If not specified, MongoDB generates an index name by concatenating the names of the indexed and ordered fields.
dropDups Boolean Create a dropDups index on a field that may have duplicates. MongoDB only indexes the first occurrence of a key and deletes all documents from the Collection that contain the next occurrence of that key. Specify true to create the dropDups index. Default value is false
sparse Boolean If true, the index only references documents with the specified field. These indexes use less space, but behave differently in some situations (in particular with sorting). Default value is false
expireAfterSeconds Integer Specify a value (in seconds), as a TTL to control how long MongoDB maintains the Documents in this Collection.
v Index version The version number of the index. The default version depends on the version of MongoDB running when creating the index
weights document Is a number in the range 1 to 99999 and represents the meaning of the field in relation to other indexed fields in terms of score.
default_language Chain With a text index, this is the language that defines the rules of the index. Default value is english
language_override Chain For a text index, specify the name of the field contained in the Document, the language to override the default language. Default value is language