Creating Indexes in MongoDB

MongoDB creates a unique index on the _id field during the creation of a collection. The _id index prevents clients from inserting two documents with the same value for the _id field. You cannot drop this index on the _id field.

>_ Types of Indexes

Simple Index

If an index is created with the one key then it is termed as simple Index.

Compound Index

If an index is created with multiple keys then it is termed as multikey or Compound Index.

>_ How To Create Indexes Manually

MongoDB provides a method named createIndex() using this we can create the index, it has an alias method named ensureIndex().


 db.collection.createIndex(keys, options)

Parameter Type Description
keys document A document that contains the field and value pairs where the field is the index key and the value describes the type of index for that field.
For an ascending index on a field, specify a value of 1; for descending index, specify a value of -1.
options document Optional. A document that contains a set of options that controls the creation of the index.

Key Options

Parameter Type Description
background boolean Optional. Builds the index in the background so that building an index does not block other database activities. Specify true to build in the background. The default value is false.
unique boolean Optional. Creates a unique index so that the collection will not accept insertion of documents where the index key or keys match an existing value in the index. Specify true to create a unique index. The default value is false.
name string Optional. The name of the index. If unspecified, MongoDB generates an index name by concatenating the names of the indexed fields and the sort order.


>_ Create a NonUniqueSimple Index for the 'users' collection on 'Age' Field.


>_ Create a Unique Simple Index for the 'users' collection on 'userid' field to prevent duplicate names.


>_ Create a Compund Unique Index for the 'users' collection on 'firstname','lastname' fields to prevent duplicate entries.