Navigation

Indexes with the mongo Shell

Overview

Indexes can support the efficient execution of queries. 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.

Use the createIndex() method to create an index on a collection. Indexes can support the efficient execution of queries. MongoDB automatically creates an index on the _id field upon the creation of a collection.

To create an index on a field or fields, pass to the createIndex() method an index key specification document that lists the fields to index and the index type for each field:

{ <field1>: <type1>, ...}
  • For an ascending index type, specify 1 for <type>.
  • For a descending index type, specify -1 for <type>.

createIndex() only creates an index if the index does not exist.

Prerequisites

The examples in this section use the restaurants collection in the test database. For instructions on populating the collection with the sample dataset, see Import Example Dataset.

In the mongo shell connected to a running mongod instance, switch to the test database.

use test

Create a Single-Field Index

Create an ascending index on the "cuisine" field of the restaurants collection.

db.restaurants.createIndex( { "cuisine": 1 } )

The method returns a document with the status of the operation.

{
  "createdCollectionAutomatically" : false,
  "numIndexesBefore" : 1,
  "numIndexesAfter" : 2,
  "ok" : 1
}

Upon successful index creation, the "numIndexesAfter" value is one greater than the "numIndexesBefore" value.

Create a compound index.

MongoDB supports compound indexes which are indexes on multiple fields. The order of the fields determine how the index stores its keys. For example, the following operation creates a compound index on the "cuisine" field and the "address.zipcode" field. The index orders its entries first by ascending "cuisine" values, and then, within each "cuisine", by descending "address.zipcode" values.

db.restaurants.createIndex( { "cuisine": 1, "address.zipcode": -1 } )

The method returns a document with the status of the operation.

{
   "createdCollectionAutomatically" : false,
   "numIndexesBefore" : 2,
   "numIndexesAfter" : 3,
   "ok" : 1
}

Upon successful index creation, the "numIndexesAfter" value is one greater than the "numIndexesBefore" value.

Additional Information

You can specify various properties for indexes, such as a unique constraint. In the MongoDB Manual, see createIndex() for the available options.

MongoDB provides different index types to support different kinds of queries and datasets. In the MongoDB Manual, see the Index Introduction for the different index types supported in MongoDB.