Indexes

Indexes support the efficient execution of queries in MongoDB. Withoutindexes, MongoDB must perform a collection scan, i.e. scan everydocument in a collection, to select those documents that match thequery statement. If an appropriate index exists for a query,MongoDB can use the index to limit the number of documents it mustinspect.

Indexes are special data structures [1] that store a smallportion of the collection’s data set in an easy to traverse form. Theindex stores the value of a specific field or set of fields, ordered bythe value of the field. The ordering of the index entries supportsefficient equality matches and range-based query operations. Inaddition, MongoDB can return sorted results by using the ordering inthe index.

The following diagram illustrates a query that selects and orders thematching documents using an index:

Diagram of a query that uses an index to select and return sorted results. The index stores ``score`` values in ascending order. MongoDB can traverse the index in either ascending or descending order to return sorted results.

Fundamentally, indexes in MongoDB are similar to indexes in otherdatabase systems. MongoDB defines indexes at the collectionlevel and supports indexes on any field or sub-field of the documentsin a MongoDB collection.

Default _id Index

MongoDB creates a unique index on the_id field during the creation of acollection. The _id index prevents clients from inserting twodocuments with the same value for the _id field. You cannot dropthis index on the _id field.

Note

In sharded clusters, if you do not usethe _id field as the shard key, then your applicationmust ensure the uniqueness of the values in the _id fieldto prevent errors. This is most-often done by using a standardauto-generated ObjectId.

Create an Index

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala

To create an index in theMongo Shell, usedb.collection.createIndex().

  1. db.collection.createIndex( <key and index type specification>, <options> )

The following example creates a single key descending index onthe name field:

  1. db.collection.createIndex( { name: -1 } )

The db.collection.createIndex method onlycreates an index if an index of the same specification doesnot already exist.

Important

To create an index on a collection in MongoDB Compass,the collection must contain documents.

To create an index inMongoDB Compass, complete the followingsteps:

  • Navigate to the collection for which you wish to createthe index:

    • In the left-hand MongoDB Compass navigation pane, clickthe database to which your target collection belongs.
    • From the database view, click the target collection name.
  • Click the Indexes tab:

Compass index tab

  • Click the Create Index button:

Compass index button

The following dialog appears:

Compass index dialog

  • (Optional) Enter the index name.

Leaving this field blank causes MongoDB Compass to create adefault name for the index.

  • Add fields to the index.

Use the Configure the index definition sectionof the dialog to define the fields for your index andtheir respective types. To create an index on multiplefields, click Add another field.

  • (Optional) Specify the index options.

The following index options can be specified:

To create an index using thePython driver,use pymongo.collection.Collection.create_index().

  1. db.collection.create_index([(<key and index type specification>)], <options> )

The following example creates a single key descending index onthe name field:

  1. collection.create_index([("name", pymongo.DESCENDING)])

The pymongo.collection.Collection.create_index()method only creates an index if an index of the samespecification does not already exist.

To create an index using theJava driver,usecom.mongodb.client.MongoCollection.createIndex.

  1. collection.createIndex( <key and index type specification>, <options> )

The following example creates a single key descending index onthe name field:

  1. collection.createIndex(Indexes.descending("name"));

The com.mongodb.client.MongoCollection.createIndex.method only creates an index if an index of the samespecification does not already exist.

To create an index using theNode.JS driver,usecreateIndex().

  1. collection.createIndex( { <key and index type specification> }, function(err, result) {
  2. console.log(result);
  3. callback(result);
  4. }

The following example creates a single key descending index onthe name field:

  1. collection.createIndex( { name : -1 }, function(err, result) {
  2. console.log(result);
  3. callback(result);
  4. }

The createIndex()method only creates an index if an index of the samespecification does not already exist.

To create an index using thePHP driver, useMongoDB\Collection::createIndex().

  1. $collection->createIndex(<key and index type specification>, <options>);

The following example creates a single key descending index onthe name field:

  1. $collection->createIndex(['name' => -1]);

The MongoDB\Collection::createIndex()method only creates an index if an index of the samespecification does not already exist.

To create an index using theMotor driver,usemotor.motor_asyncio.AsyncIOMotorCollection.create_index().

  1. await db.collection.create_index([(<key and index type specification>)], <options> )

The following example creates a single key descending index onthe name field:

  1. await collection.create_index([("name", pymongo.DESCENDING)])

The motor.motor_asyncio.AsyncIOMotorCollection.create_index()method only creates an index if an index of the samespecification does not already exist.

To create an index using theAsync Java driver,usecom.mongodb.async.client.MongoCollection.createIndex.

  1. collection.createIndex( <key and index type specification>, <options>, <callbackFunction>)

The following example creates a single key descending index onthe name field:

  1. collection.createIndex(Indexes.descending("name"), someCallbackFunction());

The com.mongodb.async.client.MongoCollection.createIndexmethod only creates an index if an index of the samespecification does not already exist.

To create an index using the.NET driver,useMongoCollection.CreateIndex.

  1. collection.CreateIndex( IndexKeys<collection>.<key and index type specification>, <options> );

The following example creates a single key descending index onthe name field:

  1. collection.CreateIndex( IndexKeys<collection>.Descending("name") );

The MongoCollection.CreateIndexmethod only creates an index if an index of the samespecification does not already exist.

To create an index using thePerl driver,usecreate_one()).

  1. my $indexes = $db->get_collection( <collection> )->indexes;
  2. $indexes->create_one( [ <key and index type specification> ] );

The following example creates a single key descending index onthe name field:

  1. my $indexes = $db->get_collection( <collection> )->indexes;
  2. $indexes->create_one( [ name => -1 ] );

The create_one())method only creates an index if an index of the samespecification does not already exist.

To create an index using theRuby driver, useMongo::Index::View#create_one.

  1. client[:collection].indexes.create_one({ <key and index type specification> }, {options})

The following example creates a single key descending index onthe name field:

  1. client[:collection].indexes.create_one({ name: -1 })

The Mongo::Index::View#create_onemethod only creates an index if an index of the samespecification does not already exist.

To create an index using theScala driver,useorg.mongodb.scala.model.Indexes.

  1. collection.createIndex(<key and index type specification>)

The following example creates a single key descending index onthe name field:

  1. collection.createIndex(descending("name"))

The org.mongodb.scala.model.Indexesmethod only creates an index if an index of the samespecification does not already exist.

[1]MongoDB indexes use a B-tree data structure.

Index Names

The default name for an index is the concatenation of the indexed keysand each key’s direction in the index ( i.e. 1 or -1) using underscoresas a separator. For example, an index created on{ item : 1, quantity: -1 } has the name item1_quantity-1.

You can create indexes with a custom name, such as one that is morehuman-readable than the default. For example, consider an applicationthat frequently queries the products collection to populate data onexisting inventory. The following createIndex()method creates an index on item and quantity named query forinventory:

  1. db.products.createIndex(
  2. { item: 1, quantity: -1 } ,
  3. { name: "query for inventory" }
  4. )

You can view index names using the db.collection.getIndexes()method. You cannot rename an index once created. Instead, you mustdrop and re-create the index with a new name.

Index Types

MongoDB provides a number of different index types to support specifictypes of data and queries.

Single Field

In addition to the MongoDB-defined _id index, MongoDB supports thecreation of user-defined ascending/descending indexes on a singlefield of a document.

Diagram of an index on the ``score`` field (ascending).

For a single-field index and sort operations, the sort order (i.e.ascending or descending) of the index key does not matter becauseMongoDB can traverse the index in either direction.

See Single Field Indexes and Sort with a Single Field Index formore information on single-field indexes.

Compound Index

MongoDB also supports user-defined indexes on multiple fields, i.e.compound indexes.

The order of fields listed in a compound index has significance. Forinstance, if a compound index consists of { userid: 1, score: -1 },the index sorts first by userid and then, within each useridvalue, sorts by score.

Diagram of a compound index on the ``userid`` field (ascending) and the ``score`` field (descending). The index sorts first by the ``userid`` field and then by the ``score`` field.

For compound indexes and sort operations, the sort order (i.e.ascending or descending) of the index keys can determine whether theindex can support a sort operation. SeeSort Order for more information on theimpact of index order on results in compound indexes.

See Compound Indexes and Sort on Multiple Fields formore information on compound indexes.

Multikey Index

MongoDB uses multikey indexes to indexthe content stored in arrays. If you index a field that holds an arrayvalue, MongoDB creates separate index entries for every element ofthe array. These multikey indexes allowqueries to select documents that contain arrays by matching on elementor elements of the arrays. MongoDB automatically determines whether tocreate a multikey index if the indexed field contains an array value;you do not need to explicitly specify the multikey type.

Diagram of a multikey index on the ``addr.zip`` field. The ``addr`` field contains an array of address documents. The address documents contain the ``zip`` field.

See Multikey Indexes and Multikey Index Boundsfor more information on multikey indexes.

Geospatial Index

To support efficient queries of geospatial coordinate data, MongoDBprovides two special indexes: 2d indexes that usesplanar geometry when returning results and 2dsphere indexes that use spherical geometry to return results.

See 2d Index Internals for a high level introduction togeospatial indexes.

Text Indexes

MongoDB provides a text index type that supports searchingfor string content in a collection. These text indexes do not storelanguage-specific stop words (e.g. “the”, “a”, “or”) and stem thewords in a collection to only store root words.

See Text Indexes for more information on text indexes andsearch.

Hashed Indexes

To support hash based sharding,MongoDB provides a hashed index type,which indexes the hash of the value of a field. These indexes have amore random distribution of values along their range, but _only_support equality matches and cannot support range-based queries.

Index Properties

Unique Indexes

The unique property for an index causesMongoDB to reject duplicate values for the indexed field. Other thanthe unique constraint, unique indexes are functionally interchangeablewith other MongoDB indexes.

Partial Indexes

New in version 3.2.

Partial indexes only index the documents ina collection that meet a specified filter expression. By indexing asubset of the documents in a collection, partial indexes have lowerstorage requirements and reduced performance costs for index creationand maintenance.

Partial indexes offer a superset of the functionality of sparse indexesand should be preferred over sparse indexes.

Sparse Indexes

The sparse property of an index ensuresthat the index only contain entries for documents that have the indexedfield. The index skips documents that do not have the indexed field.

You can combine the sparse index option with the unique index optionto prevent inserting documents that have duplicate values for the indexedfield(s) and skip indexing documents that lack the indexed field(s).

TTL Indexes

TTL indexes are special indexes that MongoDBcan use to automatically remove documents from a collection after acertain amount of time. This is ideal for certain types of informationlike machine generated event data, logs, and session information thatonly need to persist in a database for a finite amount of time.

See: Expire Data from Collections by Setting TTL for implementation instructions.

Index Use

Indexes can improve the efficiency of read operations. TheAnalyze Query Performance tutorial provides an example of theexecution statistics of a query with and without an index.

For information on how MongoDB chooses an index to use, see queryoptimizer.

Indexes and Collation

New in version 3.4.

Collation allows users to specifylanguage-specific rules for string comparison, such as rules forlettercase and accent marks.

  • Mongo Shell
  • Compass
  • Python
  • Java (Sync)
  • Node.js
  • Other
    • PHP
    • Motor
    • Java (Async)
    • C#
    • Perl
    • Ruby
    • Scala

Important

MongoDB Compass does not support collation for indexes.

The following examples illustrate indexes and collation inthe Mongo Shell.

Note

The following examples illustrate indexes and collation inthe Mongo Shell.

Refer to your driver documentation forinstructions on creating indexes with collation in your specificdriver.

Note

The following examples illustrate indexes and collation inthe Mongo Shell.

Refer to your driver documentation forinstructions on creating indexes with collation in your specificdriver.

Note

The following examples illustrate indexes and collation inthe Mongo Shell.

Refer to your driver documentation forinstructions on creating indexes with collation in your specificdriver.

Note

The following examples illustrate indexes and collation inthe Mongo Shell.

Refer to your driver documentation forinstructions on creating indexes with collation in your specificdriver.

Note

The following examples illustrate indexes and collation inthe Mongo Shell.

Refer to your driver documentation forinstructions on creating indexes with collation in your specificdriver.

Note

The following examples illustrate indexes and collation inthe Mongo Shell.

Refer to your driver documentation forinstructions on creating indexes with collation in your specificdriver.

Note

The following examples illustrate indexes and collation inthe Mongo Shell.

Refer to your driver documentation forinstructions on creating indexes with collation in your specificdriver.

Note

The following examples illustrate indexes and collation inthe Mongo Shell.

Refer to your driver documentation forinstructions on creating indexes with collation in your specificdriver.

Note

The following examples illustrate indexes and collation inthe Mongo Shell.

Refer to your driver documentation forinstructions on creating indexes with collation in your specificdriver.

Note

The following examples illustrate indexes and collation inthe Mongo Shell.

Refer to your driver documentation forinstructions on creating indexes with collation in your specificdriver.

To use an index for string comparisons, an operation must alsospecify the same collation. That is, an index with a collationcannot support an operation that performs string comparisons on theindexed fields if the operation specifies a different collation.

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

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

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

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

  1. 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 adifferent collation can still use the index to support comparisonson the index prefix keys.

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

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

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

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

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

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

For more information on collation, see the collation referencepage.

The following indexes only support simple binary comparison and donot support collation:

Covered Queries

When the query criteria and the projection of a query includeonly the indexed fields, MongoDB returns results directly fromthe index without scanning any documents or bringing documents intomemory. These covered queries can be very efficient.

Diagram of a query that uses only the index to match the query criteria and return the results. MongoDB does not need to inspect data outside of the index to fulfill the query.

For more information on covered queries, seeCovered Query.

Index Intersection

New in version 2.6.

MongoDB can use the intersection of indexes to fulfill queries. For queries thatspecify compound query conditions, if one index can fulfill a part of aquery condition, and another index can fulfill another part of thequery condition, then MongoDB can use the intersection of the twoindexes to fulfill the query. Whether the use of a compound index orthe use of an index intersection is more efficient depends on theparticular query and the system.

For details on index intersection, see Index Intersection.

Restrictions

Certain restrictions apply to indexes, such as the length of the indexkeys or the number of indexes per collection. See IndexLimitations for details.

Additional Considerations

Although indexes can improve query performances, indexes also presentsome operational considerations. See Operational Considerationsfor Indexes for more information.

Applications may encounter reduced performance during indexbuilds, including limited read/write access to the collection. Formore information on the index build process, seeIndex Builds on Populated Collections, including theIndex Builds in Replicated Environments section.

Some drivers may specify indexes, using NumberLong(1) rather than1 as the specification. This does not have any affect on theresulting index.