db.collection.createIndex()

Definition

db.collection. createIndex ( keys, options )

Creates indexes on collections.

Changed in version 3.2: MongoDB disallows the creation of version 0 indexes. To upgrade existing version 0 indexes, see Version 0 Indexes.

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.

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

Starting in 3.6, you cannot specify * as the index name.

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

The db.collection.createIndex() is a wrapper around the createIndexes command.

To minimize the impact of building an index on replica sets and sharded clusters, use a rolling index build procedure as described on Build Indexes on Replica Sets.

Options

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

Changed in version 3.4: Added support for collation option.

Options for All Index Types

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

Changed in version 3.0: The dropDups option is no longer available.

Parameter Type Description
background boolean Optional. Builds the index in the background so the operation 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 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.

Whether user specified or MongoDB generated, index names including their full namespace (i.e. database.collection) cannot be longer than the Index Name Limit.

partialFilterExpression document

Optional. If specified, the index only references 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 index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). The default value is false. See Sparse Indexes for more information.

Changed in version 3.2: Starting in MongoDB 3.2, MongoDB provides the option to create partial indexes. Partial indexes offer a superset of the functionality of sparse indexes. If you are using MongoDB 3.2 or later, partial indexes should be preferred over sparse indexes.

Changed in version 2.6: 2dsphere indexes 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.

2d, geoHaystack, and text indexes behave similarly to the 2dsphere 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 on a per-index basis when creating an index.

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.

New in version 3.0.

Option for Collation

New in version 3.4.

Warning

Collation is not supported in MongoDB 3.2 and earlier versions. In MongoDB 3.2 and earlier versions, do not create indexes with the unsupported collation option as this will block the upgrade to 3.4, which enforces a stricter validation of index options.

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

首页