翻译或纠错本页面

db.collection.createIndex()

说明

db.collection.createIndex(keys, options)

在集合中创建索引

在 3.2 版更改: Starting in MongoDB 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.

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

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.

在 3.4 版更改: Added support for collation option.

Options for All Index Types

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

在 3.0 版更改: The dropDups option is no longer available.

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.

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.

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 稀疏索引 for more information.

在 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.

在 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 通过设置TTL使集合中的数据过期 for more information on this functionality. This applies only to TTL indexes.
storageEngine document

Optional. Allows users to specify configuration to the storage engine on a per-index basis when creating an index. The value of the storageEngine option should take the following form:

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

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

3.0 新版功能.

Option for Collation

The collation option is available for all index types except for text indexes.

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.

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.

3.4 新版功能.

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 that 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.

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 通过权重控制搜索结果 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 文本搜索语言 for the available languages and 指定文本索引的语言 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 使用任意键为文档指定语言 for an example.
textIndexVersion integer

Optional. For text indexes, the text index version number. Version can be either 1 or 2.

In MongoDB 2.6, the default version is 2. MongoDB 2.4 can only support version 1.

2.6 新版功能.

Options for 2dsphere Indexes

The following option is available for 2dsphere indexes only:

Parameter Type Description
2dsphereIndexVersion integer

Optional. For 2dsphere indexes, the 2dsphere index version number. Version can be either 1 or 2.

In MongoDB 2.6, the default version is 2. MongoDB 2.4 can only support version 1.

2.6 新版功能.

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.

Behaviors

The createIndex() method has the behaviors described here.

  • 在 3.4 版更改.

    To add or change index options, other than collation, you must drop the index using the dropIndex() method and issue another createIndex() operation with the new options.

    If you create an index with one set of options, and then issue the createIndex() method with the same index fields and different options (not including collation) without first dropping the index, createIndex() will not rebuild the existing index with the new options.

    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.

  • If you call multiple createIndex() methods with the same index specification at the same time, only the first operation will succeed, all other operations will have no effect.

  • Non-background indexing operations will block all other operations on a database.

  • MongoDB will not create an index on a collection if the index entry for an existing document exceeds the Maximum Index Key Length. Previous versions of MongoDB would create the index but not index such documents.

    在 2.6 版更改.

Examples

Create an Ascending Index on a Single Field

The following example creates an ascending index on the field orderDate.

db.collection.createIndex( { orderDate: 1 } )

If the keys document specifies more than one field, then createIndex() creates a compound index.

Create an Index on a Multiple Fields

The following example creates a compound index on the orderDate field (in ascending order) and the zipcode field (in descending order.)

db.collection.createIndex( { orderDate: 1, zipcode: -1 } )

A compound index cannot include a hashed index component.

注解

The order of an index is important for supporting sort() operations using the index.

Create Indexes with Collation Specified

The following example creates an index named category_fr. The example creates the index with the collation that specifies the locale fr and comparison strength 2:

db.collection.createIndex(
   { category: 1 },
   { name: "category_fr", collation: { locale: "fr", strength: 2 } }
)

The following example creates a compound index named date_category_fr with a collation. The collation applies only to the index keys with string values.

db.collection.createIndex(
   { orderDate: 1, category: 1 },
   { name: "date_category_fr", collation: { locale: "fr", strength: 2 } }
)

The collation applies to the indexed keys whose values are string.

For queries or sort operations on the indexed keys that uses the same collation rules, MongoDB can use the index.

Additional Information