Navigation
This version of the documentation is archived and no longer supported.

Indexes

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

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

The following diagram illustrates a query that selects and orders the matching 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 other database systems. MongoDB defines indexes at the collection level and supports indexes on any field or sub-field of the documents in a MongoDB collection.

Default _id Index

MongoDB creates a unique index on the _id field during the creation of a collection. The _id index prevents clients from inserting two documents with the same value for the _id field. You cannot drop this index on the _id field.

Note

In sharded clusters, if you do not use the _id field as the shard key, then your application must ensure the uniqueness of the values in the _id field to prevent errors. This is most-often done by using a standard auto-generated ObjectId.

Create an Index

To create an index in the Mongo Shell, use db.collection.createIndex().

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

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

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

The db.collection.createIndex method only creates an index if an index of the same specification does not already exist.

Important

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

To create an index in MongoDB Compass, complete the following steps:

  1. Navigate to the collection for which you wish to create the index:

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

    Compass index tab

  3. Click the Create Index button:

    Compass index button

    The following dialog appears:

    Compass index dialog
  4. (Optional) Enter the index name.

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

  5. Add fields to the index.

    Use the Configure the index definition section of the dialog to define the fields for your index and their respective types. To create an index on multiple fields, click Add another field.

  6. (Optional) Specify the index options.

    The following index options can be specified:

  7. Click Create to create the index.

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

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

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

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

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

To create an index using the Java driver, use com.mongodb.client.MongoCollection.createIndex.

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

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

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

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

To create an index using the Node.JS driver, use createIndex().

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

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

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

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

To create an index using the PHP driver, use MongoDB\Collection::createIndex().

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

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

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

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

To create an index using the Motor driver, use motor.motor_asyncio.AsyncIOMotorCollection.create_index().

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

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

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

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

To create an index using the Async Java driver, use com.mongodb.async.client.MongoCollection.createIndex.

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

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

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

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

To create an index using the .NET driver, use MongoCollection.CreateIndex.

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

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

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

The MongoCollection.CreateIndex method only creates an index if an index of the same specification does not already exist.

To create an index using the Perl driver, use create_one().

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

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

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

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

To create an index using the Ruby driver, use Mongo::Index::View#create_one.

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

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

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

The Mongo::Index::View#create_one method only creates an index if an index of the same specification does not already exist.

To create an index using the Scala driver, use org.mongodb.scala.model.Indexes.

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

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

collection.createIndex(descending("name"))

The org.mongodb.scala.model.Indexes method only creates an index if an index of the same specification does not already exist.

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

Index Types

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

Single Field

In addition to the MongoDB-defined _id index, MongoDB supports the creation of user-defined ascending/descending indexes on a single field 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 because MongoDB can traverse the index in either direction.

See Single Field Indexes and Sort with a Single Field Index for more 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. For instance, if a compound index consists of { userid: 1, score: -1 }, the index sorts first by userid and then, within each userid value, 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 the index can support a sort operation. See Sort Order for more information on the impact of index order on results in compound indexes.

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

Multikey Index

MongoDB uses multikey indexes to index the content stored in arrays. If you index a field that holds an array value, MongoDB creates separate index entries for every element of the array. These multikey indexes allow queries to select documents that contain arrays by matching on element or elements of the arrays. MongoDB automatically determines whether to create 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 Bounds for more information on multikey indexes.

Geospatial Index

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

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

Text Indexes

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

See Text Indexes for more information on text indexes and search.

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 a more 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 causes MongoDB to reject duplicate values for the indexed field. Other than the unique constraint, unique indexes are functionally interchangeable with other MongoDB indexes.

Partial Indexes

New in version 3.2.

Partial indexes only index the documents in a collection that meet a specified filter expression. By indexing a subset of the documents in a collection, partial indexes have lower storage requirements and reduced performance costs for index creation and maintenance.

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

Sparse Indexes

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

You can combine the sparse index option with the unique index option to reject documents that have duplicate values for a field but ignore documents that do not have the indexed key.

TTL Indexes

TTL indexes are special indexes that MongoDB can use to automatically remove documents from a collection after a certain amount of time. This is ideal for certain types of information like machine generated event data, logs, and session information that only 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. The Analyze Query Performance tutorial provides an example of the execution statistics of a query with and without an index.

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

Indexes and Collation

New in version 3.4.

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.

Important

MongoDB Compass does not support collation for indexes.

The following examples illustrate indexes and collation in the Mongo Shell.

Note

The following examples illustrate indexes and collation in the Mongo Shell.

Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.

Note

The following examples illustrate indexes and collation in the Mongo Shell.

Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.

Note

The following examples illustrate indexes and collation in the Mongo Shell.

Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.

Note

The following examples illustrate indexes and collation in the Mongo Shell.

Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.

Note

The following examples illustrate indexes and collation in the Mongo Shell.

Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.

Note

The following examples illustrate indexes and collation in the Mongo Shell.

Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.

Note

The following examples illustrate indexes and collation in the Mongo Shell.

Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.

Note

The following examples illustrate indexes and collation in the Mongo Shell.

Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.

Note

The following examples illustrate indexes and collation in the Mongo Shell.

Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.

Note

The following examples illustrate indexes and collation in the Mongo Shell.

Refer to your driver documentation for instructions on creating indexes with collation in your specific driver.

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

For more information on collation, see the collation reference page.

The following indexes only support simple binary comparison and do not support collation:

Covered Queries

When the query criteria and the projection of a query include only the indexed fields, MongoDB returns results directly from the index without scanning any documents or bringing documents into memory. 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, see Covered Query.

Index Intersection

New in version 2.6.

MongoDB can use the intersection of indexes to fulfill queries. For queries that specify compound query conditions, if one index can fulfill a part of a query condition, and another index can fulfill another part of the query condition, then MongoDB can use the intersection of the two indexes to fulfill the query. Whether the use of a compound index or the use of an index intersection is more efficient depends on the particular query and the system.

For details on index intersection, see Index Intersection.

Restrictions

Certain restrictions apply to indexes, such as the length of the index keys or the number of indexes per collection. See Index Limitations for details.

Additional Considerations

Although indexes can improve query performances, indexes also present some operational considerations. See Operational Considerations for Indexes for more information.

If your collection holds a large amount of data, and your application needs to be able to access the data while building the index, consider building the index in the background, as described in Background Construction.

For more information on the index build process, see Index Build Operations on a Populated Collection, including the Build Indexes on Replica Sets and Sharded Clusters section.

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