- Frequently Asked Questions >
- FAQ: Indexes
FAQ: Indexes¶
On this page
This document addresses some common questions regarding MongoDB indexes. For more information on indexes, see Indexes.
How do I create an index?¶
To create an index on a collection, use the
db.collection.createIndex()
method. Creating an index is an
administrative operation. In general, applications should not call
db.collection.createIndex()
on a regular basis.
Note
Index builds can impact performance; see How does an index build affect database performance?. Administrators should consider the performance implications before building indexes.
How does an index build affect database performance?¶
When building an index on a collection, the database that holds the collection is unavailable for read or write operations until the index build completes. If you need to build a large index, consider building the index in the background. See Index Build Operations and Build Indexes on Replica Sets.
To return information on currently running index creation operations,
see Active Indexing Operations. To kill a running index creation
operation, see db.killOp()
. The partially built index will be
deleted.
How do I see what indexes exist on a collection?¶
To list a collection’s indexes, use the
db.collection.getIndexes()
method.
How can I see if a query uses an index?¶
To inspect how MongoDB processes a query, use the
explain()
method.
How do I determine which fields to index?¶
A number of factors determine which fields to index, including selectivity, the support for multiple query shapes, and size of the index. For more information, see Operational Considerations for Indexes and Indexing Strategies.
How can I see the size of an index?¶
The db.collection.stats()
includes an
indexSizes
document which provides size
information for each index on the collection.
Depending on its size, an index may not fit into RAM. An index fits into RAM when your server has enough RAM available for both the index and the rest of the working set. When an index is too large to fit into RAM, MongoDB must read the index from disk, which is a much slower operation than reading from RAM.
In certain cases, an index does not need to fit entirely into RAM. For details, see Indexes that Hold Only Recent Values in RAM.
How do write operations affect indexes?¶
Write operations may require updates to indexes:
- If a write operation modifies an indexed field, MongoDB updates all indexes that have the modified field as a key.
- When running with the MMAPv1 storage engine, if an update to a document causes the document to grow past its allocated record size, MongoDB moves the document to a new record and updates all indexes that refer to the document, regardless of the field modified.
Therefore, if your application is write-heavy, indexes might affect performance.