Navigation
This version of the documentation is archived and no longer supported.

db.collection.createIndexes()

Definition

db.collection.createIndexes([keyPatterns, ]options)

Important

mongo Shell Method

This page documents a mongo method. This is not the documentation for database commands or language-specific drivers, such as Node.js. To use the database command, see the createIndexes command.

For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.

New in version 3.2.

Creates one or more indexes on a collection.

Parameter Type Description
keyPatterns document

An array containing index specification documents. Each document contains 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.

MongoDB supports several different index types including text, geospatial, and hashed indexes. See index types for more information.

Changed in version 4.2: MongoDB 4.2 wildcard indexes support workloads where users query against custom fields or a large variety of fields in a collection:

  • To create a wildcard index on all fields and subfields in a document, specify { "$**" : 1 } as the index key. You cannot specify a descending index key when creating a wildcard index.

    You can also either include or exclude specific fields and their subfields from the index using the optional wildcardProjection parameter.

    Wildcard indexes omit the _id field by default. To include the _id field in the wildcard index, you must explicitly include it in the wildcardProjection document:

    {
      "wildcardProjection" : {
        "_id" : 1,
        "<field>" : 0|1
      }
    }
    

    With the exception of explicitly including _id field, you cannot combine inclusion and exclusion statements in the wildcardProjection document.

  • You can create a wildcard index on a specific field and its subpaths by specifying the full path to that field as the index key and append "$**" to the path:

    { "path.to.field.$**" : 1 }

    You cannot specify a descending index key when creating a wildcard index.

    The path-specific wildcard index syntax is incompatible with the wildcardProjection option. You cannot specify additional inclusions or exclusions on the specified path.

The wildcard index key must use one of the syntaxes listed above. For example, you cannot specify a compound index key. For more complete documentation on wildcard indexes, including restrictions on their creation, see Wildcard Index Restrictions.

The mongod featureCompatibilityVersion must be 4.2 to create wildcard indexes. For instructions on setting the fCV, see Set Feature Compatibility Version on MongoDB 4.2 Deployments.

For more information on creating wildcard indexes, see Wildcard Indexes.

options document Optional. A document that contains a set of options that controls the creation of the indexes. See Options for details.

Options

The options document contains a set of options that control the creation of the indexes. Different index types can have additional options specific for that type.

Multiple index options can be specified in the same document. However, if you specify mutiple option documents the db.collection.createIndexes() operation will fail.

Consider the following db.collection.createIndexes() operation:

db.collection.createIndexes(
   [
     {
       "a": 1
     },
     {
       "b": 1
     }
   ],
   {
     unique: true,
     sparse: true,
     expireAfterSeconds: 3600
   }
 )

If the options specification had been split into multiple documents like this: { unique: true }, { sparse: true, expireAfterSeconds: 3600 } the index creation operation would have failed.

Important

When you specify options to db.collection.createIndexes(), the options apply to all of the specified indexes. For example, if you specify a collation option, all of the created indexes will include that collation.

db.collection.createIndexes() will return an error if you attempt to create indexes with incompatible options or too many arguments. Refer to the option descriptions for more information.

Options for All Index Types

The following options are available for all index types unless otherwise specified:

Parameter Type Description
unique boolean

Optional. Specifies that each index specified in the keyPatterns array is a unique index. Unique indexes will not accept insertion or update of documents where the index key value matches an existing value in the index.

Specify true to create a unique index. The default value is false.

The option is unavailable for hashed indexes.

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.

Changed in MongoDB 4.2

Starting in version 4.2, for featureCompatibilityVersion set to "4.2" or greater, MongoDB removes the Index Name Length limit of 127 byte maximum. In previous versions or MongoDB versions with featureCompatibilityVersion (fCV) set to "4.0", index names must fall within the limit.

Options specified to db.collection.createIndexes apply to all of the index specifications included in the key pattern array. Since index names must be unique, you may only specify name if you are creating a single index using db.collection.createIndexes.

partialFilterExpression document

Optional. If specified, the indexes only reference documents that match the filter expression. See Partial Indexes for more information.

A filter expression can include:

You can specify a partialFilterExpression option for all MongoDB index types.

New in version 3.2.

sparse boolean

Optional. If true, the indexes only reference documents with the specified fields. These indexes use less space but behave differently in some situations (particularly sorts). The default value is false. See Sparse Indexes for more information.

The following index types are sparse by default and ignore this option:

For a compound index that includes 2dsphere index key(s) along with keys of other types, only the 2dsphere index fields determine whether the index references a document.

Tip

Partial indexes offer a superset of the functionality of sparse indexes. Unless your application has a specific requirement, use partial indexes instead of sparse indexes.

expireAfterSeconds integer Optional. Specifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection. See Expire Data from Collections by Setting TTL for more information on this functionality. This applies only to TTL indexes.
storageEngine document

Optional. Allows users to configure the storage engine for the created indexes.

The storageEngine option should take the following form:

storageEngine: { <storage-engine-name>: <options> }

Storage engine configuration options specified when creating indexes are validated and logged to the oplog during replication to support replica sets with members that use different storage engines.

Option for Collation

Parameter Type Description
collation document

Optional. Specifies the collation for the index.

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.

If you have specified a collation at the collection level, then:

  • If you do not specify a collation when creating the index, MongoDB creates the index with the collection’s default collation.
  • If you do specify a collation when creating the index, MongoDB creates the index with the specified collation.

The collation option has the following syntax:

collation: {
   locale: <string>,
   caseLevel: <boolean>,
   caseFirst: <string>,
   strength: <int>,
   numericOrdering: <boolean>,
   alternate: <string>,
   maxVariable: <string>,
   backwards: <boolean>
}

When specifying collation, the locale field is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.

New in version 3.4.

The following indexes only support simple binary comparison and do not support collation:

Tip

To create a text, a 2d, or a geoHaystack index on a collection that has a non-simple collation, you must explicitly specify {collation: {locale: "simple"} } when creating the index.

Collation and Index Use

If you have specified a collation at the collection level, then:

  • If you do not specify a collation when creating the index, MongoDB creates the index with the collection’s default collation.
  • If you do specify a collation when creating the index, MongoDB creates the index with the specified collation.

Tip

By specifying a collation strength of 1 or 2, you can create a case-insensitive index. Index with a collation strength of 1 is both diacritic- and case-insensitive.

Unlike other index options, you can create multiple indexes on the same key(s) with different collations. To create indexes with the same key pattern but different collations, you must supply unique index names.

To use an index for string comparisons, an operation must also specify the same collation. That is, an index with a collation cannot support an operation that performs string comparisons on the indexed fields if the operation specifies a different collation.

For example, the collection myColl has an index on a string field category with the collation locale "fr".

db.myColl.createIndex( { category: 1 }, { collation: { locale: "fr" } } )

The following query operation, which specifies the same collation as the index, can use the index:

db.myColl.find( { category: "cafe" } ).collation( { locale: "fr" } )

However, the following query operation, which by default uses the “simple” binary collator, cannot use the index:

db.myColl.find( { category: "cafe" } )

For a compound index where the index prefix keys are not strings, arrays, and embedded documents, an operation that specifies a different collation can still use the index to support comparisons on the index prefix keys.

For example, the collection myColl has a compound index on the numeric fields score and price and the string field category; the index is created with the collation locale "fr" for string comparisons:

db.myColl.createIndex(
   { score: 1, price: 1, category: 1 },
   { collation: { locale: "fr" } } )

The following operations, which use "simple" binary collation for string comparisons, can use the index:

db.myColl.find( { score: 5 } ).sort( { price: 1 } )
db.myColl.find( { score: 5, price: { $gt: NumberDecimal( "10" ) } } ).sort( { price: 1 } )

The following operation, which uses "simple" binary collation for string comparisons on the indexed category field, can use the index to fulfill only the score: 5 portion of the query:

db.myColl.find( { score: 5, category: "cafe" } )

Options for text Indexes

The following options are available for text indexes only:

Parameter Type Description
weights document Optional. For text indexes, a document that contains field and weight pairs. The weight is an integer ranging from 1 to 99,999 and denotes the significance of the field relative to the other indexed fields in terms of the score. You can specify weights for some or all the indexed fields. See Control Search Results with Weights to adjust the scores. The default value is 1.
default_language string Optional. For text indexes, the language that determines the list of stop words and the rules for the stemmer and tokenizer. See Text Search Languages for the available languages and Specify a Language for Text Index for more information and examples. The default value is english.
language_override string Optional. For text indexes, the name of the field, in the collection’s documents, that contains the override language for the document. The default value is language. See Use any Field to Specify the Language for a Document for an example.
textIndexVersion integer

Optional. The text index version number. Users can use this option to override the default version number.

For available versions, see Versions.

Options for 2dsphere Indexes

The following option is available for 2dsphere indexes only:

Parameter Type Description
2dsphereIndexVersion integer

Optional. The 2dsphere index version number. Users can use this option to override the default version number.

For the available versions, see Versions.

Options for 2d Indexes

The following options are available for 2d indexes only:

Parameter Type Description
bits integer

Optional. For 2d indexes, the number of precision of the stored geohash value of the location data.

The bits value ranges from 1 to 32 inclusive. The default value is 26.

min number Optional. For 2d indexes, the lower inclusive boundary for the longitude and latitude values. The default value is -180.0.
max number Optional. For 2d indexes, the upper inclusive boundary for the longitude and latitude values. The default value is 180.0.

Options for geoHaystack Indexes

The following option is available for geoHaystack indexes only:

Parameter Type Description
bucketSize number

For geoHaystack indexes, specify the number of units within which to group the location values; i.e. group in the same bucket those location values that are within the specified number of units to each other.

The value must be greater than 0.

Options for wildcard indexes

The following option is available for wildcard indexes only:

Parameter Type Description
wildcardProjection document

Optional. Allows users to include or exclude specific field paths from the wildcard index. This option is only valid if creating a wildcard index.

The wildcardProjection option takes the following form:

wildcardProjection: {
  "path.to.field.a" : <value>,
  "path.to.field.b" : <value>
}

The <value> can be either of the following:

  • 1 or true to include the field in the wildcard index.
  • 0 or false to exclude the field from the wildcard index.

Wildcard indexes omit the _id field by default. To include the _id field in the wildcard index, you must explicitly include it in the wildcardProjection document:

{
  "wildcardProjection" : {
    "_id" : 1,
    "<field>" : 0|1
  }
}

With the exception of explicitly including _id field, you cannot combine inclusion and exclusion statements in the wildcardProjection document.

Options specified to db.collection.createIndexes apply to all of the index specifications included in the key pattern array. Specify wildcardProjection only if you are creating a single wildcard index using db.collection.createIndexes.

Behaviors

Concurrency

Changed in version 4.2.

MongoDB uses an optimized build process that obtains and holds an exclusive lock on the specified collection at the start and end of the index build. All subsequent operations on the collection must wait until createIndexes releases the exclusive lock. createIndexes allows interleaving read and write operations during the majority of the index build.

For more information on the locking behavior of createIndexes, see Index Builds on Populated Collections.

Recreating an Existing Index

If you call db.collection.createIndexes() for an index or indexes that already exist, MongoDB does not recreate the existing index or indexes.

Index Options

Non-Collation Options

With the exception of the collation option, if you create an index with one set of index options and then try to recreate the same index but with different index options, MongoDB will not change the options nor recreate the index.

To change these index options, drop the existing index with db.collection.dropIndex() before running db.collection.createIndexes() with the new options.

Collation Option

Unlike other index options, you can create multiple indexes on the same key(s) with different collations. To create indexes with the same key pattern but different collations, you must supply unique index names.

Wildcard Indexes

New in version 4.2.

For examples of wildcard index creation, see Create a Wildcard Index. For complete documentation on Wildcard Indexes, see Wildcard Indexes.

Example

See also

db.collection.createIndex() for examples of various index specifications.

Create Indexes Without Options

Consider a restaurants collection containing documents that resemble the following:

{
   location: {
      type: "Point",
      coordinates: [-73.856077, 40.848447]
   },
   name: "Morris Park Bake Shop",
   cuisine: "Cafe",
   borough: "Bronx",
}

The following example creates two indexes on the restaurants collection: an ascending index on the borough field and a 2dsphere index on the location field.

db.restaurants.createIndexes([{"borough": 1}, {"location": "2dsphere"}])

Create Indexes with Collation Specified

The following example creates two indexes on the products collection: an ascending index on the manufacturer field and an ascending index on the category field. Both indexes use a collation that specifies the locale fr and comparison strength 2:

db.products.createIndexes( [ { "manufacturer": 1}, { "category": 1 } ],
   { collation: { locale: "fr", strength: 2 } })

For queries or sort operations on the indexed keys that uses the same collation rules, MongoDB can use the index. For details, see Collation and Index Use.

Create a Wildcard Index

New in version 4.2: The mongod featureCompatibilityVersion must be 4.2 to create wildcard indexes. For instructions on setting the fCV, see Set Feature Compatibility Version on MongoDB 4.2 Deployments.

For complete documentation on Wildcard Indexes, see Wildcard Indexes.

The following lists examples of wildcard index creation:

Create a Wildcard Index on a Single Field Path

Consider a collection products_catalog where documents may contain a product_attributes field. The product_attributes field can contain arbitrary nested fields, including embedded documents and arrays:

{
  "_id" : ObjectId("5c1d358bf383fbee028aea0b"),
  "product_name" : "Blaster Gauntlet",
  "product_attributes" : {
     "price" : {
       "cost" : 299.99
       "currency" : USD
     }
     ...
  }
},
{
  "_id" : ObjectId("5c1d358bf383fbee028aea0c"),
  "product_name" : "Super Suit",
  "product_attributes" : {
     "superFlight" : true,
     "resistance" : [ "Bludgeoning", "Piercing", "Slashing" ]
     ...
  },
}

The following operation creates a wildcard index on the product_attributes field:

use inventory
db.products_catalog.createIndexes(
  [ { "product_attributes.$**" : 1 } ]
)

With this wildcard index, MongoDB indexes all scalar values of product_attributes. If the field is a nested document or array, the wildcard index recurses into the document/array and indexes all scalar fields in the document/array.

The wildcard index can support arbitrary single-field queries on product_attributes or one of its nested fields:

db.products_catalog.find( { "product_attributes.superFlight" : true } )
db.products_catalog.find( { "product_attributes.maxSpeed" : { $gt : 20 } } )
db.products_catalog.find( { "product_attributes.elements" : { $eq: "water" } } )

Note

The path-specific wildcard index syntax is incompatible with the wildcardProjection option. See the parameter documentation for more information.

Create a Wildcard Index on All Field Paths

Consider a collection products_catalog where documents may contain a product_attributes field. The product_attributes field can contain arbitrary nested fields, including embedded documents and arrays:

{
  "_id" : ObjectId("5c1d358bf383fbee028aea0b"),
  "product_name" : "Blaster Gauntlet",
  "product_attributes" : {
     "price" : {
       "cost" : 299.99
       "currency" : USD
     }
     ...
  }
},
{
  "_id" : ObjectId("5c1d358bf383fbee028aea0c"),
  "product_name" : "Super Suit",
  "product_attributes" : {
     "superFlight" : true,
     "resistance" : [ "Bludgeoning", "Piercing", "Slashing" ]
     ...
  },
}

The following operation creates a wildcard index on all scalar fields (excluding the _id field):

use inventory
db.products_catalog.createIndexes(
  [ { "$**" : 1 } ]
)

With this wildcard index, MongoDB indexes all scalar fields for each document in the collection. If a given field is a nested document or array, the wildcard index recurses into the document/array and indexes all scalar fields in the document/array.

The created index can support queries on any arbitrary field within documents in the collection:

db.products_catalog.find( { "product_price" : { $lt : 25 } } )
db.products_catalog.find( { "product_attributes.elements" : { $eq: "water" } } )

Note

Wildcard indexes omit the _id field by default. To include the _id field in the wildcard index, you must explicitly include it in the wildcardProjection document. See parameter documentation for more information.

Create a Wildcard Index on Multiple Specific Field Paths

Consider a collection products_catalog where documents may contain a product_attributes field. The product_attributes field can contain arbitrary nested fields, including embedded documents and arrays:

{
  "_id" : ObjectId("5c1d358bf383fbee028aea0b"),
  "product_name" : "Blaster Gauntlet",
  "product_attributes" : {
     "price" : {
       "cost" : 299.99
       "currency" : USD
     }
     ...
  }
},
{
  "_id" : ObjectId("5c1d358bf383fbee028aea0c"),
  "product_name" : "Super Suit",
  "product_attributes" : {
     "superFlight" : true,
     "resistance" : [ "Bludgeoning", "Piercing", "Slashing" ]
     ...
  },
}

The following operation creates a wildcard index and uses the wildcardProjection option to include only scalar values of the product_attributes.elements and product_attributes.resistance fields in the index.

use inventory
db.products_catalog.createIndexes(
  [ { "$**" : 1 } ],
  {
    "wildcardProjection" : {
      "product_attributes.elements" : 1,
      "product_attributes.resistance" : 1
    }
  }
)

While the key pattern "$**" covers all fields in the document, the wildcardProjection field limits the index to only the included fields. For complete documentation on wildcardProjection, see Options for wildcard indexes.

If a field is a nested document or array, the wildcard index recurses into the document/array and indexes all scalar fields in the document/array.

The created index can support queries on any scalar field included in the wildcardProjection:

db.products_catalog.find( { "product_attributes.elements" : { $eq: "Water" } } )
db.products_catalog.find( { "product_attributes.resistance" : "Bludgeoning" } )

Note

Wildcard indexes do not support mixing inclusion and exclusion statements in the wildcardProjection document except when explicitly including the _id field. For more information on wildcardProjection, see the parameter documentation.

Create a Wildcard Index that Excludes Multiple Specific Field Paths

Consider a collection products_catalog where documents may contain a product_attributes field. The product_attributes field can contain arbitrary nested fields, including embedded documents and arrays:

{
  "_id" : ObjectId("5c1d358bf383fbee028aea0b"),
  "product_name" : "Blaster Gauntlet",
  "product_attributes" : {
     "price" : {
       "cost" : 299.99
       "currency" : USD
     }
     ...
  }
},
{
  "_id" : ObjectId("5c1d358bf383fbee028aea0c"),
  "product_name" : "Super Suit",
  "product_attributes" : {
     "superFlight" : true,
     "resistance" : [ "Bludgeoning", "Piercing", "Slashing" ]
     ...
  },
}

The following operation creates a wildcard index and uses the wildcardProjection document to index all scalar fields for each document in the collection, excluding the product_attributes.elements and product_attributes.resistance fields:

use inventory
db.products_catalog.createIndexes(
  [ { "$**" : 1 } ],
  {
    "wildcardProjection" : {
      "product_attributes.elements" : 0,
      "product_attributes.resistance" : 0
    }
  }
)

While the key pattern "$**" covers all fields in the document, the wildcardProjection field excludes the specified fields from the index. For complete documentation on wildcardProjection, see Options for wildcard indexes.

If a field is a nested document or array, the wildcard index recurses into the document/array and indexes all scalar fields in the document/array.

The created index can support queries on any scalar field except those excluded by wildcardProjection:

db.products_catalog.find( { "product_attributes.maxSpeed" : { $gt: 25 } } )
db.products_catalog.find( { "product_attributes.superStrength" : true } )

Note

Wildcard indexes do not support mixing inclusion and exclusion statements in the wildcardProjection document except when explicitly including the _id field. For more information on wildcardProjection, see the parameter documentation.

Additional Information

For additional information about indexes, refer to: