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

Create an Index

Indexes allow MongoDB to process and fulfill queries quickly by creating small and efficient representations of the documents in a collection. Users can create indexes for any collection on any field in a document. By default, MongoDB creates an index on the _id field of every collection.

This tutorial describes how to create an index on a single field. MongoDB also supports compound indexes, which are indexes on multiple fields. See Create a Compound Index for instructions on building compound indexes.

Create an Index on a Single Field

To create an index, use ensureIndex() or a similar method from your driver. The ensureIndex() method only creates an index if an index of the same specification does not already exist.

For example, the following operation creates an index on the userid field of the records collection:

db.records.ensureIndex( { userid: 1 } )

The value of the field in the index specification describes the kind of index for that field. For example, a value of 1 specifies an index that orders items in ascending order. A value of -1 specifies an index that orders items in descending order. For additional index types, see Index Types.

The created index will support queries that select on the field userid, such as the following:

db.records.find( { userid: 2 } )
db.records.find( { userid: { $gt: 10 } } )

But the created index does not support the following query on the profile_url field:

db.records.find( { profile_url: 2 } )

For queries that cannot use an index, MongoDB must scan all documents in a collection for documents that match the query.

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. To build indexes on replica sets, see the Build Indexes on Replica Sets section for more information.

Note

To build or rebuild indexes for a replica set see Build Indexes on Replica Sets.

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

See also

Create a Compound Index, Indexing Tutorials and Index Concepts for more information.