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.
创建单字段索引时,必须指定以下详细信息:
要在其上创建索引的字段
索引值的排序顺序为升序或降序
注意
默认的_id_索引就是单字段索引的一个示例。 创建新集合时,会在_id字段上自动创建此索引。
样本数据
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.
创建单字段索引
使用MongoDB\Collection::createIndex()方法创建单字段索引。 以下示例在title字段上按升序创建索引:
$indexName = $collection->createIndex(['title' => 1]);
以下是前面代码示例中创建的索引涵盖的查询示例:
$document = $collection->findOne(['title' => 'Sweethearts']); echo json_encode($document), PHP_EOL;
更多信息
要查看演示如何管理索引的可运行示例,请参阅《查询优化索引》。
To learn more about single field indexes, see Single Field Indexes in the MongoDB Server manual.
API 文档
要进一步了解本指南所讨论的任何方法,请参阅以下 API 文档: