Navigation

createIndexes

New in version 2.6.

Definition

createIndexes

Builds one or more indexes on a collection.

Changed in version 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.

The createIndexes command takes the following form:

db.runCommand(
  {
    createIndexes: <collection>,
    indexes: [
        {
            key: {
                <key-value_pair>,
                <key-value_pair>,
                ...
            },
            name: <index_name>,
            <option1>,
            <option2>,
            ...
        },
        { ... },
        { ... }
    ]
  }
)

The createIndexes command takes the following fields:

Field Type Description
createIndexes string The collection for which to create indexes.
indexes array Specifies the indexes to create. Each document in the array specifies a separate index.

Each document in the indexes array can take the following fields:

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

Field Type Description
key document Specifies the index’s fields. For each field, specify a key-value pair in which the key is the name of the field to index and the value is either the index direction or index type. If specifying direction, specify 1 for ascending or -1 for descending.
name string A name that uniquely identifies the index.
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.

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.

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

New in version 2.6.

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 only supports version 1.

New in version 2.6.

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

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.

Considerations

An index name, including the namespace, cannot be longer than the Index Name Length limit.

Behavior

Concurrency

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

Multiple Index Builds

Changed in version 3.0.0.

If you specify multiple indexes to the createIndexes command, the operation only scans the collection once, and if at least one index is to be built in the foreground, the operation will build all the specified indexes in the foreground.

Memory Usage Limit

Changed in version 3.4: You can build one or more indexes on a collection with the database command createIndexes. The default limit on memory usage for a createIndexes operation is 500 megabytes. You can override this limit by setting the maxIndexBuildMemoryUsageMegabytes server parameter.

createIndexes uses a combination of memory and temporary files on disk to complete index builds. Once the memory limit is reached, createIndexes uses temporary disk files in a subdirectory named _tmp within the --dbpath directory for additional scratch space. The higher the memory limit is set, the faster the index build can complete, but be careful not to set this limit too high relative to available RAM or your system can run out of free memory.

Index Options

With the exception of the collation option, if you create an index with one set of options and then issue createIndexes with the same index fields but different options, MongoDB will not change the options nor rebuild the index. To change these index options, drop the existing index with db.collection.dropIndex() before running the new createIndexes with the new options.

Collation Option

New in version 3.4.

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

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" } )

Example

The following command builds two indexes on the inventory collection of the products database:

db.getSiblingDB("products").runCommand(
  {
    createIndexes: "inventory",
    indexes: [
        {
            key: {
                item: 1,
                manufacturer: 1,
                model: 1
            },
            name: "item_manufacturer_model",
            unique: true
        },
        {
            key: {
                item: 1,
                supplier: 1,
                model: 1
            },
            name: "item_supplier_model",
            unique: true
        }
    ]
  }
)

When the indexes successfully finish building, MongoDB returns a results document that includes a status of "ok" : 1.

Output

The createIndexes command returns a document that indicates the success of the operation. The document contains some but not all of the following fields, depending on outcome:

createIndexes.createdCollectionAutomatically

If true, then the collection didn’t exist and was created in the process of creating the index.

createIndexes.numIndexesBefore

The number of indexes at the start of the command.

createIndexes.numIndexesAfter

The number of indexes at the end of the command.

createIndexes.ok

A value of 1 indicates the indexes are in place. A value of 0 indicates an error.

createIndexes.note

This note is returned if an existing index or indexes already exist. This indicates that the index was not created or changed.

createIndexes.errmsg

Returns information about any errors.

createIndexes.code

The error code representing the type of error.

←   create currentOp  →