Index Considerations and Management
On this page
Overview
In this guide, you can learn about using indexes to improve the efficiency of your queries and add functionality to querying and storing documents.
Without a relevant index, MongoDB scans every document in a collection to find the documents that match a query. These collection scans are slow and can negatively affect the performance of your application. However, if the appropriate index exists, MongoDB can use the index to reduce the number of documents to inspect.
Operational Considerations
To improve query performance, build indexes on fields that appear often in your application's queries or operations that return sorted results. Each index that you add consumes disk space and memory, so we recommend that you track memory and disk usage when doing capacity planning. In addition, when a write operation updates an indexed field, MongoDB updates the related index, which can negatively impact performance for write operations.
You can use wildcard indexes in your MongoDB application to query against fields whose names are not known in advance or are arbitrary. Wildcard indexes are not designed to replace workload-based index planning.
To learn more about designing your data model and choosing indexes, see the Indexes section of the Operational Factors and Data Models guide in the MongoDB Server manual.
Sample Data
The examples in this guide use the movies
collection in the
sample_mflix
database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and
load the sample datasets, see the Get Started with Atlas guide.
Create an Index
MongoDB supports several index types to help query your data. The following pages describe different index types and provide sample code to programmatically create each type of index.
List Indexes
You can retrieve a list of indexes on a collection by calling the
MongoDB\Collection::listIndexes()
method:
foreach ($collection->listIndexes() as $indexInfo) { echo $indexInfo; }
Remove an Index
You can remove any unused index except the default unique index on the
_id
field.
The following sections provide examples that show how to remove one or more indexes from a collection.
Delete a Single Index
Pass the name of an index to the MongoDB\Collection::dropIndex()
method to remove an index from a collection.
The following example removes the '_title_'
index from the
movies
collection:
$collection->dropIndex('_title_');
Note
You cannot remove a single field from a compound index. You must drop the entire index and create a new one to update the indexed fields.
Delete All Indexes
You can delete all indexes by calling the
MongoDB\Collection::dropIndexes()
method on a collection:
$collection->dropIndexes();
The dropIndexes()
method returns information about the number of
indexes removed and a success message.
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API documentation: