索引
索引支持在 MongoDB 中高效执行查询。 如果没有索引,MongoDB 必须执行collection扫描,即扫描collection中的每个文档,以选择与查询声明匹配的文档。如果查询存在适当的索引,MongoDB 就可以使用该索引来限制必须检查的文档数量。
PHP 驱动程序支持通过MongoDB\Collection
类管理索引,该类实现 MongoDB 的跨驱动程序 索引管理 和 枚举索引 规格。
本文档介绍如何使用 MongoDB PHP 库创建、列出和删除索引。 MongoDB 手册的索引参考提供了有关 MongoDB 中索引的更全面信息。
创建索引
使用MongoDB\Collection::createIndex()
或MongoDB\Collection::createIndexes()
方法创建索引。 有关每种方法的更多详细信息,请参阅方法参考。
以下示例使用createIndex()
方法在state
字段上创建升序索引:
$collection = (new MongoDB\Client)->test->zips; $result = $collection->createIndex(['state' => 1]); var_dump($result);
创建索引时,该方法会返回索引的名称,该名称是根据其规范自动生成的。 上面的示例会输出类似以下内容:
string(7) "state_1"
列出索引
MongoDB\Collection::listIndexes()
方法提供有关collection中索引的信息。MongoDB\Collection::listIndexes()
方法返回MongoDB\Model\IndexInfo
对象的迭代器,您可以使用该迭代器查看有关每个索引的信息。 有关更多详细信息,请参阅方法参考。
以下示例列出了test
数据库的zips
collection中的所有索引:
$collection = (new MongoDB\Client)->test->zips; foreach ($collection->listIndexes() as $indexInfo) { var_dump($indexInfo); }
输出类似如下所示:
object(MongoDB\Model\IndexInfo)#10 (4) { ["v"]=> int(1) ["key"]=> array(1) { ["_id"]=> int(1) } ["name"]=> string(4) "_id_" ["ns"]=> string(9) "test.zips" } object(MongoDB\Model\IndexInfo)#13 (4) { ["v"]=> int(1) ["key"]=> array(1) { ["state"]=> int(1) } ["name"]=> string(7) "state_1" ["ns"]=> string(9) "test.zips" }
dropIndexes
MongoDB\Collection::dropIndex()
方法允许您删除单个索引,而MongoDB\Collection::dropIndexes()
则删除collection上的所有索引。有关每种方法的更多详细信息,请参阅方法参考。
以下示例按名称state_1
删除单个索引:
$collection = (new MongoDB\Client)->test->zips; $result = $collection->dropIndex('state_1'); var_dump($result);
该操作的输出类似于:
object(MongoDB\Model\BSONDocument)#11 (1) { ["storage":"ArrayObject":private]=> array(2) { ["nIndexesWas"]=> int(2) ["ok"]=> float(1) } }