定义
参数
$indexes: array要在集合上创建的索引。
例如,以下内容指定了对
username字段的唯一索引以及对email和createdAt字段的复合索引:[ [ 'key' => [ 'username' => -1 ], 'unique' => true ], [ 'key' => [ 'email' => 1, 'createdAt' => 1 ] ], ] $options: array指定所需选项的数组。
名称类型说明comment
混合
commitQuorum
字符串|整数
指定在主节点将索引标记为就绪之前,副本集的多少个承载数据的节点(包括主节点)必须成功完成索引构建。
此选项接受写关注(write
wconcern)中相同的字段值加上"votingMembers",这表示所有投票数据承载节点。4.4 之前的服务器版本不支持此功能,如果使用,将导致执行时出现异常。
1.7版本新增。
maxTimeMS
整型
The cumulative time limit in milliseconds for processing operations on the cursor. MongoDB aborts the operation at the earliest following interrupt point.
1.3版本新增。
会话
与操作相关联的客户端会话。
1.3版本新增。
writeConcern
Write concern to use for the operation. Defaults to the collection's write concern.
无法将单个操作的写关注(write concern)指定为ACID 事务的一部分。相反,请在启动ACID 事务时设立
writeConcern选项。
Return Values
以字符串数组形式表示的所创建索引的名称。
错误/异常
MongoDB\Exception\UnsupportedException,如果所选服务器使用了选项但不支持选项(例如collation、readConcern、writeConcern)。
MongoDB\Exception\InvalidArgumentException 用于与参数或选项解析相关的错误。
MongoDB\ 驱动程序\Exception\RuntimeException 用于扩展级别的其他错误(例如连接错误)。
行为
$indexes parameter
The $indexes parameter is an array of index specification documents. Each element in $indexes must itself be an array or object with a key field, which corresponds to the $key parameter of createIndex(). The array or object may include other fields that correspond to index options accepted by createIndex(). For a full list of the supported index creation options, refer to the createIndexes command reference in the MongoDB manual.
例如,以下$indexes参数会创建两个索引。 第一个是username字段上的升序唯一索引,第二个是loc字段上具有自定义名称的 2dsphere 索引:
[ [ 'key' => [ 'username' => 1 ], 'unique' => true ], [ 'key' => [ 'loc' => '2dsphere' ], 'name' => 'geo_index' ], ]
例子
以下示例在test数据库中的restaurantscollection上创建了两个索引。一个索引是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 command reference in the MongoDB manual
MongoDB 手册中的索引文档