createIndex() – Create one or more indexes on a collection command

Creates a new index on a specific field of a collection

Syntax diagram

Read syntax diagramSkip visual syntax diagramdb.collection. createIndex(indexSpec[indexOptions])

Command arguments

indexSpec
Required and optional arguments for use in creating the index:
field
  • Required
  • Specifies a field in the document on which the index is to be created.
  • Can include a data type definition.
sortorder
  • Optional
  • Possible values: 1 | -1
  • If the argument is set to 1, order is ascending. This is the default setting.
  • If the argument is set to -1, order is descending.
indexName
  • Required
  • Specifies a name for an index.
  • If no value is specified for indexName, a name is generated.
expireAfterSeconds
  • Optional
  • Specifies a value, in seconds, at which point the documents in the specified collection are deleted
expireAt
  • Optional
  • Specifies an expiration date/time for the operation.
unique
  • Optional.
  • Specifies whether the index is unique.
  • Possible values: true | false
indexOption
name
  • Required.
  • The name of the index, specified by indexName.
  • If no value is specified for name, a name is generated.
array
  • Required.
  • Specifies whether array elements are allowed in the index.
  • Possible values: true | false.
  • Default value: false
unique
  • Required.
  • Specifies whether the index is unique on the collection.
  • Possible values: true | false.
  • Default value: false

Examples

The following example shows the command syntax for creating an index on the field, author, in ascending order, by using the default type string with a default length of 50, from the collection, books:
db.books.createIndex({"author": 1})
The following example shows the successful output from running the createIndex operation on the field, author:
Index <books_xauthor> was created successfully.
The following example shows the command syntax for creating an index on the field, category, with a type value of string and a field length of 40:
db.books.createIndex({"category": [1, "$string", 40]})
The following example shows the successful output from running the createIndex command on the field category:
Index <books_xcategory> was created successfully.
The following example shows the command syntax for creating an index on the field price, with the type value in descending order, and a name value of mypriceidx.
db.books.createIndex({"price": [-1, "$number"]}, “mypriceidx”)
The following example shows the successful output from running the createIndex command on the field price:
Index <mypriceidx> was created successfully.