Single Field Indexes
Overview
Single field indexes are indexes with a reference to a single field of a document in a collection. These indexes improve single field query and sort performance. They also support TTL Indexes that automatically remove documents from a collection after a certain amount of time or at a specified clock time.
When creating a single-field index, you must specify the following details:
The field on which to create the index
The sort order for the indexed values as either ascending or descending
Note
The default _id_
index is an example of a single-field index.
This index is automatically created on the _id
field when a new
collection is created.
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 Single-Field Index
Use the MongoDB\Collection::createIndex()
method to create a single
field index. The following example creates an index in ascending order on the
title
field:
$indexName = $collection->createIndex(['title' => 1]);
The following is an example of a query that is covered by the index created in the preceding code example:
$document = $collection->findOne(['title' => 'Sweethearts']); echo json_encode($document), PHP_EOL;
{"_id":...,"plot":"A musical comedy duo...", "genres":["Musical"],...,"title":"Sweethearts",...}
Additional Information
To view runnable examples that demonstrate how to manage indexes, see Optimize Queries by Using Indexes.
To learn more about single field indexes, see Single Field Indexes in the MongoDB Server manual.
API Documentation
To learn more about any of the methods discussed in this guide, see the following API documentation: