MongoDB - Indexing

MongoDB - Indexing

Indexes support efficient query resolution. Without indexes, MongoDB must scan each document in the collection to select those documents that match the query. This scan is extremely inefficient and requires MongoDB to process a large amount of data.

Indexes are special data structures that store a small portion of a set of data in an easy-to-browse form. An index stores the value of a specific field or set of fields, ordered by the value of the field specified in the index.

sureIndex() method

To create an index, you need to use MongoDB's ensureIndex() method.

Syntax

The basic syntax of the sureIndex() method is as follows().

> db . COLLECTION_NAME . ensureIndex ({ KEY : 1 })

Here key is the name of the field you want to create an index on and 1 is for ascending. To create an index in descending order, you need to use -1.

example

> db . mycol . ensureIndex ({ "title" : 1 }) >

In the sureIndex() method, you can pass multiple fields to create an index on multiple fields.

> db . mycol . ensureIndex ({ "title" : 1 , "description" :- 1 }) >

The sureIndex() method also accepts a list of options (which are optional). Following is the list −