Docs 菜单
Docs 主页
/ /

单字段索引

单字段索引是引用集合中文档的单个字段的索引。 这些索引提高了单字段查询和排序性能。 它们还支持 TTL索引,可在一定时间后或指定的时钟时间自动从集合删除文档。

创建单字段索引时,必须指定以下详细信息:

  • 要在其上创建索引的字段

  • 索引值的排序顺序为升序或降序

注意

默认的 _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;
{"_id":...,"plot":"A musical comedy duo...",
"genres":["Musical"],...,"title":"Sweethearts",...}

要查看演示如何管理索引的可运行示例,请参阅 用于查询优化的索引。

要学习;了解有关单字段索引的更多信息,请参阅MongoDB Server手册中的单字段索引

要进一步了解本指南所讨论的任何方法,请参阅以下 API 文档:

后退

索引管理

在此页面上