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:

  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 .