MongoDB with drivers
This page documents a mongosh method. To see the equivalent method in a MongoDB driver, see the corresponding page for your programming language:
Definition
db.collection.createIndexes( [ keyPatterns ], options, commitQuorum )Creates one or more indexes on a collection.
db.collection.createIndexes()takes the following parameters:Parameter Type Description keyPatternsdocument
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:
See index types for more information.
Wildcard indexes support workloads where users query against custom fields or a large variety of fields in a collection:
You can create a wildcard index on a specific field and its subpaths or on all of the fields in a document.
For details see, Wildcard Indexes.
optionsdocument
Optional. A document that contains a set of options that controls the creation of the indexes. See Options for details.
integer or string
Optional. The minimum number of data-bearing voting replica set members (i.e. commit quorum), including the primary, that must report a successful index build before the primary marks the
indexesas ready. A "voting" member is any replica set member wheremembers[n].votesis greater than0.Supports the following values:
"votingMembers"- all data-bearing voting replica set members (Default)."majority"- a simple majority of data-bearing voting replica set members.<int>- a specific number of data-bearing voting replica set members.0- Disables quorum-voting behavior. Members start the index build simultaneously but do not vote or wait for quorum before completing the index build. If you start an index build with a commit quorum of0, you cannot later modify the commit quorum usingsetIndexCommitQuorum.- A replica set tag name.
Compatibility
This method is available in deployments hosted in the following environments:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
Note
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
- MongoDB Enterprise: The subscription-based, self-managed version of MongoDB
- MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB
Stable API
When using Stable API V1:
You cannot specify any of the following fields in the
optionsdocument:backgroundbucketSizesparsestorageEngine
- You cannot create text indexes.
The above unsupported index types are ignored by the query planner in strict mode. For example, attempting to use a
sparseindex withcursor.hint()will result in the followingBadValueerror:planner returned error :: caused by :: hint provided does not
correspond to an existing indexOptions
The
optionsdocument 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 multiple 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 uniqueboolean
Optional. Specifies that each index specified in the
keyPatternsarray 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
trueto create a unique index. The default value isfalse.The option is unavailable for hashed indexes.
namestring
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.
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 usingdb.collection.createIndexes().partialFilterExpressiondocument
Optional. If specified, the indexes only reference documents that match the filter expression. See Partial Indexes for more information.
A filter expression can include:
- equality expressions (i.e.
field: valueor using the$eqoperator), $exists: trueexpression,$gt,$gte,$lt,$lteexpressions,$typeexpressions,$andoperator,$oroperator,$inoperator
You can specify a
partialFilterExpressionoption for all MongoDB index types.sparseboolean
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 isfalse. See Sparse Indexes for more information.The following index types are sparse by default and ignore this option:
For a compound index that includes
2dsphereindex keys and keys for other types, only the2dsphereindex fields determine whether the index references a document.Partial indexes have a superset of the sparse index functionality. Unless your application has a specific requirement, use partial indexes instead of sparse indexes.
expireAfterSecondsinteger
Optional. Specifies a value, in seconds, as a time to live (TTL) to control how long MongoDB retains documents in this collection. This option only applies to TTL indexes. See Expire Data from Collections by Setting TTL for more information.
If you use TTL indexes created before MongoDB 5.0, or if you want to sync data created in MongDB 5.0 with a pre-5.0 installation, see Indexes Configured Using NaN to avoid misconfiguration issues.
The TTL index
expireAfterSecondsvalue must be within0and2147483647inclusive.boolean
Optional. A flag that determines whether the index is hidden from the query planner. A hidden index is not evaluated as part of the query plan selection.
Default is
false.storageEnginedocument
Optional. Allows users to configure the storage engine for the created indexes.
The
storageEngineoption 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 collationdocument
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
localefield is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.The following indexes only support simple binary comparison and do not support collation:
Tip
To create a
textor2dindex 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
strengthof1or2, you can create a case-insensitive index. Index with a collationstrengthof1is both diacritic- and case-insensitive.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.
Warning
Because indexes that are configured with collation use ICU collation keys to achieve sort order, collation-aware index keys may be larger than index keys for indexes without collation.
A
restaurantscollection has the following documents:db.restaurants.insertMany( [
{ _id: 1, category: "café", status: "Open" },
{ _id: 2, category: "cafe", status: "open" },
{ _id: 3, category: "cafE", status: "open" }
] )The
restaurantscollection has an index on a string fieldcategorywith the collation locale"fr".db.restaurants.createIndex( { category: 1 }, { collation: { locale: "fr" } } )The following query, which specifies the same collation as the index, can use the index:
db.restaurants.find( { category: "cafe" } ).collation( { locale: "fr" } )However, the following query operation, which by default uses the "simple" binary collator, cannot use the index:
db.restaurants.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
restaurantshas a compound index on the numeric fieldsscoreandpriceand the string fieldcategory; the index is created with the collation locale"fr"for string comparisons:db.restaurants.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.restaurants.find( { score: 5 } ).sort( { price: 1 } )
db.restaurants.find( { score: 5, price: { $gt: Decimal128( "10" ) } } ).sort( { price: 1 } )The following operation, which uses
"simple"binary collation for string comparisons on the indexedcategoryfield, can use the index to fulfill only thescore: 5portion of the query:db.restaurants.find( { score: 5, category: "cafe" } )To confirm whether a query used an index, run the query with the
explain()option.Important
Matches against document keys, including embedded document keys, use simple binary comparison. This means that a query for a key like "type.café" will not match the key "type.cafe", regardless of the value you set for the strength parameter.
Options for
textIndexesThe following options are available for text indexes only:
Parameter Type Description weightsdocument
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 Assign Weights to Text Search Results on Self-Managed Deployments to adjust the scores. The default value is
1.Starting in MongoDB 5.0, the weights option is only allowed for text indexes.
default_languagestring
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 on Self-Managed Deployments for the available languages and Specify the Default Language for a Text Index on Self-Managed Deployments for more information and examples. The default value is
english.language_overridestring
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 Specify the Default Language for a Text Index on Self-Managed Deployments for an example.textIndexVersioninteger
Optional. The
textindex version number. Users can use this option to override the default version number.For available versions, see Text Index Versions on Self-Managed Deployments.
Options for
2dsphereIndexesThe following option is available for 2dsphere indexes only:
Parameter Type Description 2dsphereIndexVersioninteger
Optional. The
2dsphereindex version number. Users can use this option to override the default version number.For the available versions, see 2dsphere Indexes.
Options for
2dIndexesThe following options are available for
2dindexes only:Parameter Type Description bitsinteger
Optional. For
2dindexes, the number of precision of the stored geohash value of the location data.The
bitsvalue ranges from 1 to 32 inclusive. The default value is26.minnumber
Optional. For
2dindexes, the lower inclusive boundary for the longitude and latitude values. The default value is-180.0.maxnumber
Optional. For
2dindexes, the upper inclusive boundary for the longitude and latitude values. The default value is180.0.Options for
wildcardindexesThe following option is available for wildcard indexes only:
Parameter Type Description wildcardProjectiondocument
Optional. Allows users to include or exclude specific field paths from a wildcard index.
This option is only valid when you create an wildcard index on all document fields. You cannot specify the
wildcardProjectionoption when you create a wildcard index on a specific field path and its subfields.wildcardProjectionworks with specifications like:{ "$**": 1 }
{ "userID":, "$**": 1 }However, you can't define an index that includes the same field in the wildcard fields and the regular (non-wildcard) fields. To define the index correctly, use a
wildcardProjectionto exclude duplicated fields from the wildcard pattern.wildcardProjectiondoes not work with a specification like:``{ "path.to.field.$**" : 1 }``The
wildcardProjectionoption takes the following form:wildcardProjection: {
"path.to.field.a" : <value>,
"path.to.field.b" : <value>
}The
<value>can be either of the following:1ortrueto include the field in the wildcard index.0orfalseto exclude the field from the wildcard index.
Wildcard indexes omit the
_idfield by default. To include the_idfield in the wildcard index, you must explicitly include it in thewildcardProjectiondocument:{
"wildcardProjection" : {
"_id" : 1,
"<field>" : 0|1
}
}All of the statements in the
wildcardProjectiondocument must be either inclusion or exclusion statements. You can also include the_idfield with exclusion statements. This is the only exception to the rule.Options specified to
db.collection.createIndexes()apply to all of the index specifications included in the key pattern array. SpecifywildcardProjectiononly if you are creating a single wildcard index usingdb.collection.createIndexes().Behaviors
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 and Non-Hidden 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.
The hidden option can be changed without dropping and recreating the index. See Hidden Option.
To change the other index options, drop the existing index with
db.collection.dropIndex()before runningdb.collection.createIndexes()with the new options.Collation Option
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.
Hidden Option
To hide or unhide existing indexes, you can use the following
mongoshmethods:For example,
To change the
hiddenoption for an index totrue, use thedb.collection.hideIndex()method:db.restaurants.hideIndex( { borough: 1, ratings: 1 } );To change the
hiddenoption for an index tofalse, use thedb.collection.unhideIndex()method:db.restaurants.unhideIndex( { borough: 1, city: 1 } );
Tip
Wildcard Indexes
Wildcard indexes omit the
_idfield by default. To include the_idfield in the wildcard index, you must explicitly include it in thewildcardProjectiondocument:{
"wildcardProjection" : {
"_id" : 1,
"<field>" : 0|1
}
}All of the statements in the
wildcardProjectiondocument must be either inclusion or exclusion statements. You can also include the_idfield with exclusion statements. This is the only exception to the rule.Wildcard indexes do not support:
- 2d (Geospatial) indexes
- 2dsphere (Geospatial) indexes
- Hashed indexes
- Time to Live (TTL) indexes
- Text indexes
- Unique indexes
Wildcard indexes are sparse indexes. They do not support queries when an indexed field does not exist. A wildcard index will index the document if the wildcard field has a
nullvalue.Starting in MongoDB 7.0, wildcard indexes support ascending (
1) and descending (-1) sort order. Earlier versions only supported ascending order.
To learn more, see:
Transactions
You can create collections and indexes inside a distributed transaction if the transaction is not a cross-shard write transaction.
To use
db.collection.createIndexes()in a transaction, the transaction must use read concern"local". If you specify a read concern level other than"local", the transaction fails.Index Builds
Changed in version 7.1.
Starting in MongoDB 7.1, index builds are improved with faster error reporting and increased failure resilience. You can also set the minimum available disk space required for index builds using the new
indexBuildMinAvailableDiskSpaceMBparameter, which stops index builds if disk space is too low.The following table compares the index build behavior starting in MongoDB 7.1 with earlier versions.
Behavior Starting in MongoDB 7.1 Behavior in Earlier MongoDB Versions Index errors found during the collection scan phase, except duplicate key errors, are returned immediately and then the index build stops. Earlier MongoDB versions return errors in the commit phase, which occurs near the end of the index build. MongoDB 7.1 helps you to rapidly diagnose index errors. For example, if an incompatible index value format is found, the error is returned to you immediately.
Index build errors can take a long time to be returned compared to MongoDB 7.1 because the errors are returned near the end of the index build in the commit phase.
Increased resilience for your deployment. If an index build error occurs, a secondary member can request that the primary member stop an index build and the secondary member does not crash. A request to stop an index build is not always possible: if a member has already voted to commit the index, then the secondary cannot request that the index build stop and the secondary crashes (similar to MongoDB 7.0 and earlier).
An index build error can cause a secondary member to crash.
Improved disk space management for index builds. An index build may be automatically stopped if the available disk space is below the minimum specified in the
indexBuildMinAvailableDiskSpaceMBparameter. If a member has already voted to commit the index, then the index build is not stopped.An index build is not stopped if there is insufficient available disk space.
Example
Tip
db.collection.createIndex()for examples of various index specifications.Create Indexes Without Options
Consider a
restaurantscollection containing documents that resemble the following:db.restaurants.insertOne (
{
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
restaurantscollection: an ascending index on theboroughfield and a 2dsphere index on thelocationfield.db.restaurants.createIndexes([{"borough": 1}, {"location": "2dsphere"}])Create Indexes with Collation Specified
The following example creates two indexes on the
productscollection: an ascending index on themanufacturerfield and an ascending index on thecategoryfield. Both indexes use a collation that specifies the localefrand comparison strength2: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
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
- Create a Wildcard Index on All Field Paths
- Create a Wildcard Index on Multiple Specific Field Paths
- Omit Specific Fields from Wildcard Index Coverage
Create a Wildcard Index on a Single Field Path
Consider a collection
products_catalogwhere documents may contain aproduct_attributesfield. Theproduct_attributesfield can contain arbitrary nested fields, including embedded documents and arrays:db.products_catalog.insertMany( [
{
_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_attributesfield: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_attributesor 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
wildcardProjectionoption. See the parameter documentation for more information.Create a Wildcard Index on All Field Paths
Consider a collection
products_catalogwhere documents may contain aproduct_attributesfield. Theproduct_attributesfield can contain arbitrary nested fields, including embedded documents and arrays:db.products_catalog.insertMany( [
{
_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
_idfield):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
_idfield by default. To include the_idfield in the wildcard index, you must explicitly include it in thewildcardProjectiondocument. See parameter documentation for more information.Create a Wildcard Index on Multiple Specific Field Paths
Consider a collection
products_catalogwhere documents may contain aproduct_attributesfield. Theproduct_attributesfield can contain arbitrary nested fields, including embedded documents and arrays:db.products_catalog.insertMany( [
{
_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
wildcardProjectionoption to include only scalar values of theproduct_attributes.elementsandproduct_attributes.resistancefields in the index.use inventory
db.products_catalog.createIndexes(
[ { "$**" : 1 } ],
{
"wildcardProjection" : {
"product_attributes.elements" : 1,
"product_attributes.resistance" : 1
}
}
)The pattern
"$**"includes all fields in the document. Use thewildcardProjectionfield to limit the index to the specified fields.For complete documentation on
wildcardProjection, see Options forwildcardindexes.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 wildcard index supports 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
wildcardProjectiondocument except when explicitly including the_idfield. For more information onwildcardProjection, see the parameter documentation.Omit Specific Fields from Wildcard Index Coverage
Consider a collection
products_catalogwhere documents may contain aproduct_attributesfield. Theproduct_attributesfield can contain arbitrary nested fields, including embedded documents and arrays:db.products_catalog.insertMany( [
{
_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" ]
}
}
] )This example uses a wildcard index and a
wildcardProjectiondocument to index the scalar fields for each document in the collection. The wildcard index excludes theproduct_attributes.elementsandproduct_attributes.resistancefields:use inventory
db.products_catalog.createIndexes(
[ { "$**" : 1 } ],
{
"wildcardProjection" : {
"product_attributes.elements" : 0,
"product_attributes.resistance" : 0
}
}
)The wildcard pattern
"$**"includes all of the fields in the document. However, thewildcardProjectionfield excludes the specified fields from the index.For complete documentation on
wildcardProjection, see Options forwildcardindexes.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 index can support queries on any scalar field except fields that are 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
wildcardProjectiondocument except when explicitly including the_idfield. For more information onwildcardProjection, see the parameter documentation.Create Indexes With Commit Quorum
Note
Requires featureCompatibilityVersion 4.4+
Each
mongodin the replica set or sharded cluster must have featureCompatibilityVersion set to at least4.4to start index builds simultaneously across replica set members.Index builds on a replica set or sharded cluster build simultaneously across all data-bearing replica set members. For sharded clusters, the index build occurs only on shards containing data for the collection being indexed. The primary requires a minimum number of data-bearing
votingmembers (i.e commit quorum), including itself, that must complete the build before marking the index as ready for use. See Index Builds in Replicated Environments for more information.To set the commit quorum, use
createIndexes()to specify thecommitQuorumvalue.commitQuorumspecifies how many data-bearing voting members, or which voting members, including the primary, must be prepared to commit the index build before the primary will execute the commit. The default commit quorum isvotingMembers, which means all data-bearing members.The following operation creates an index with a commit quorum of
"majority":db.getSiblingDB("examples").invoices.createIndexes(
{ "invoices" : 1 },
{ },
"majority"
)The primary marks index build as ready only after a simple majority of data-bearing voting members "vote" to commit the index build. For more information on index builds and the voting process, see Index Builds in Replicated Environments.
Create Multiple Indexes
Create a
cakeSalescollection that contains cake sales in the states of California (CA) and Washington (WA):db.cakeSales.insertMany( [
{ _id: 0, type: "chocolate", orderDate: new Date("2020-05-18T14:10:30Z"),
state: "CA", price: 13, quantity: 120 },
{ _id: 1, type: "chocolate", orderDate: new Date("2021-03-20T11:30:05Z"),
state: "WA", price: 14, quantity: 140 },
{ _id: 2, type: "vanilla", orderDate: new Date("2021-01-11T06:31:15Z"),
state: "CA", price: 12, quantity: 145 },
{ _id: 3, type: "vanilla", orderDate: new Date("2020-02-08T13:13:23Z"),
state: "WA", price: 13, quantity: 104 },
{ _id: 4, type: "strawberry", orderDate: new Date("2019-05-18T16:09:01Z"),
state: "CA", price: 41, quantity: 162 },
{ _id: 5, type: "strawberry", orderDate: new Date("2019-01-08T06:12:03Z"),
state: "WA", price: 43, quantity: 134 }
] )The following example creates multiple indexes on the
cakeSalescollection:db.cakeSales.createIndexes( [
{ "type": 1 },
{ "orderDate": 1 },
{ "state": 1 },
{ "orderDate": 1, "state": -1 }
] )The first three indexes are on single fields and in ascending order (
1).The last index is on
orderDatein ascending order (1) andstatein descending order (-1).Additional Information
For additional information about indexes, refer to:
- The Indexes section of this manual for full documentation of indexes and indexing in MongoDB.
db.collection.getIndexes()to view the specifications of existing indexes for a collection.Text Indexes on Self-Managed Deployments for details on creating
textindexes.- Geospatial Indexes for geospatial queries.
- TTL Indexes for expiration of data.
- equality expressions (i.e.