MongoDB\Collection::createIndexes()
定义
参数
$indexes
: array要创建的集合索引。
例如,以下指定了对
username
字段的唯一索引和对email
和createdAt
字段的组合索引。[ [ 'key' => [ 'username' => -1 ], 'unique' => true ], [ 'key' => [ 'email' => 1, 'createdAt' => 1 ] ], ] $options
: array指定所需选项的数组。
名称类型描述commentmixedcommitQuorumstring|integer指定主节点在标记索引为就绪之前,必须成功完成包括主节点在内的多少个副本集数据承载成员的索引构建。
此选项接受写关注中
w
字段以及"votingMembers"
相同的值,后者表示所有投票数据承载节点。此功能不支持4.4版本之前的服务器,如果使用将导致执行时抛出异常。
新功能自版本1.7.
maxTimeMS整数处理游标上操作的总时间限制(毫秒)。MongoDB将在下一个中断点后终止操作。
新功能自版本1.3.
session与操作关联的客户端会话。
新功能自版本1.3.
writeConcern
返回值
创建的索引名称,作为字符串数组。
错误/异常
如果使用不支持的选项(例如 collation
、readConcern
、writeConcern
),将抛出 MongoDB\Exception\UnsupportedException
。
与参数或选项解析相关的错误将抛出 MongoDB\Exception\InvalidArgumentException
。
其他扩展级别的错误(例如连接错误)将抛出 MongoDB\Driver\Exception\RuntimeException。
行为
$indexes
参数
$indexes
参数是一个索引规范文档数组。在 $indexes
中的每个元素都必须自身是一个数组或对象,并且包含一个 key
字段,该字段对应于 createIndex()
方法的 $key
参数。数组或对象可以包含其他字段,这些字段对应于 createIndex()
接受的索引选项。有关支持创建索引选项的完整列表,请参阅 MongoDB 手册中的 createIndexes 命令参考。
例如,以下 $indexes
参数创建两个索引。第一个是在 username
字段上的升序唯一索引,第二个是在 loc
字段上的自定义名称的 2dsphere 索引。
[ [ 'key' => [ 'username' => 1 ], 'unique' => true ], [ 'key' => [ 'loc' => '2dsphere' ], 'name' => 'geo_index' ], ]
示例
以下示例在 test
数据库中的 restaurants
集合上创建两个索引。一个是在 borough
和 cuisine
字段上的复合索引,另一个是在 loc
字段上的自定义名称的 2dsphere 索引。
$collection = (new MongoDB\Client)->selectCollection('test', 'restaurants'); $indexNames = $collection->createIndexes([ [ 'key' => [ 'borough' => 1, 'cuisine' => 1] ], [ 'key' => [ 'loc' => '2dsphere'], 'name' => 'geo_index' ], ]); var_dump($indexNames);
输出将类似于
array(2) { [0]=> string(19) "borough_1_cuisine_1" [1]=> string(9) "geo_index" }
另请参阅
createIndexes 命令参考 MongoDB 手册
索引 文档 MongoDB 手册