Latest web development tutorials

MongoDB index

The index is usually possible to greatly improve the efficiency of the query, if there is no index, MongoDB when reading data must scan each file in the collection and select those records that match the query criteria.

This scan whole collection query efficiency is very low, especially when dealing with large amounts of data, queries can take tens of seconds or even minutes, the performance of this site is very deadly.

Index is a special data structure, the index is stored in a data set of easy-to-read traversal, the index value is a structure of a database table or columns to sort

ensureIndex () method

MongoDB uses ensureIndex () method to create the index.


ensureIndex () method basic syntax is as follows:


Grammar Key index field value you want to create an index for the specified create ascending, descending if you want to create an index of -1 can be specified.



ensureIndex () method, you can also set up to use multiple fields to create an index (relational database called a composite index).


ensureIndex () receives the optional parameters, optional parameters are listed below:

Parameter Type Description
background Boolean Indexing process will block other database operations, create indexes background can be specified later stage system, an increase of "background" optional parameters. "background" The default value isfalse.
unique Boolean The indexing is unique. Specifies to create a unique index to true. The default value isfalse.
name string Name of the index. If not specified, MongoDB by connecting the index field name and sort order to generate an index name.
dropDups Boolean Delete duplicate records when you create a unique index, specify true to create a unique index. The default value isfalse.
sparse Boolean For field data does not exist in the document do not enable the index; this parameter requires special attention, if set to true, then the index field does not query the document does not contain a corresponding field .. The default value isfalse.
expireAfterSeconds integer Specify a value in seconds for the unit to complete the TTL setting, set the survival time of collection.
v index version Index version number. The default version of the index depends on the run when mongod create an index version.
weights document Index weights, values ​​between 1 to 99,999, represents the right to score another index field with respect to the weight of the index.
default_language string For text indexes, this parameter determines the stop words and stemming the rules and word lists. The default is English
language_override string For text index, which specifies the field names contained in the document, the language override the default language, the default value is language.


Create an index in the background:

db.values.ensureIndex({open: 1, close: 1}, {background: true})

By adding background when creating an index: true option, allowing to create work in the background