Docs Menu

Docs HomeDevelop ApplicationsMongoDB Manual

Create an Index

On this page

  • About this Task
  • Procedure
  • Example
  • Results
  • Learn More

Indexes support efficient execution of queries in MongoDB. If your application is repeatedly running queries on the same fields, you can create an index on those fields to improve performance for those queries.

To create an index, use the createIndex() shell method or equivalent method for your driver. This page shows examples for the MongoDB Shell and drivers.

When you run a create index command in the MongoDB Shell or a driver, MongoDB only creates the index if an index of the same specification does not exist.

Although indexes improve query performance, adding an index has negative performance impact for write operations. For collections with a high write-to-read ratio, indexes are expensive because each insert and update must also update any indexes.


To set the language of the examples on this page, use the Select your language drop-down menu in the right navigation pane.


Note

Index Sort Order

For a single-field index, the sort order (ascending or descending) of the index key does not matter because MongoDB can traverse the index in either direction.

To confirm that the index was created, use mongosh to run the db.collection.getIndexes() method:

db.collection.getIndexes()

Output:

[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{ v: 2, key: { name: -1 }, name: 'name_-1' }
]

To view information on created indexes using a driver, refer to your driver's documentation.

←  IndexesSpecify an Index Name →