ensureIndex() - Creates a new index

Creates a new index on a specific field of a collection.

Syntax diagram

Read syntax diagramSkip visual syntax diagramdb.collection. ensureIndex(indexSpec indexName ,unique )
Read syntax diagramSkip visual syntax diagramdb.collection. ensureIndex(indexSpec indexOptions )

Command arguments

indexSpec
This argument specifies a field in the document on which the index is to be created. It might include a data type definition
indexName
This argument specifies a name for an index. A name is generated if it is not specified.
expireAfterSeconds
Optional. Specifies a value, in seconds, at which point the documents in this collection are deleted
expireAt
Optional.
unique (true | false)
This optional argument specifies whether the index is unique.
indexOptions
This optional argument can have one of the following options:
name
This argument specifies a name of an index. A name is generated if not specified.
array (true | false)
This argument specifies an array of elements.
unique (true | false)
This argument specifies whether the index is unique.

Example

Example 1: Create an index on field 'author' in ascending order, by using the default type string with default length 50.
db.books.ensureIndex({"author": 1})
Sample output:
Index <books_xauthor> was created successfully.
Example 2: Create an index on field 'category' with type string and field length 40.
db.books.ensureIndex({"category": [1, "$string", 40]})
Sample output:
Index <books_xcategory> was created successfully.
Example 3: Create an index on field price with type number in descending order, name it mypriceidx.
db.books.ensureIndex({"price": [-1, "$number"]}, “mypriceidx”)
Sample output:
Index <mypriceidx> was created successfully.