For AI agents: a documentation index is available at https://www.mongodb.com/ja-jp/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
MongoDB Branding Shape
Click here >
Docs Menu

Single Field Indexes

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.

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 deployment and load the sample datasets, see the MongoDB Get Started guide.

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",...}

To view runnable examples that demonstrate how to manage indexes, see Indexes for Query Optimization.

To learn more about single field indexes, see Single Field Indexes in the MongoDB Server manual.

To learn more about any of the methods discussed in this guide, see the following API documentation: