On this page
Indexes
On this page
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:
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
- Mongo Shell
- Compass
- Python
- Java (Sync)
- Node.js
- Other
- PHP
- Motor
- Java (Async)
- C#
- Perl
- Ruby
- Scala
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:
Navigate to the collection for which you wish to create the index:
- In the left-hand MongoDB Compass navigation pane, click the database to which your target collection belongs.
- From the database view, click the target collection name.
Click the Indexes tab:
Click the Create Index button:
The following dialog appears:
(Optional) Enter the index name.
Leaving this field blank causes MongoDB Compass to create a default name for the index.
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.
(Optional) Specify the index options.
The following index options can be specified:
- Build index in the background
- Create a unique index
- Create TTL
- Partial filter expression
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 .