定义
参数
$key: array|object指定要索引的一个或多个字段以及索引顺序。
例如,以下内容指定
username字段的降序索引:[ 'username' => -1 ] $options: array指定所需选项的数组。
The
$optionsparameter accepts both index and command options. A non-exhaustive list of index options follows. For a complete list of index options, refer to the createIndexes command reference in the MongoDB manual.指数选项(非详尽)
排序规则数组|对象Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. When specifying collation, thelocalefield is mandatory; all other collation fields are optional. For descriptions of the fields, see Collation Document.If the collation is unspecified but the collection has a default collation, the operation uses the collation specified for the collection. If no collation is specified for the collection or for the operation, MongoDB uses the simple binary comparison used in prior versions for string comparisons.expireAfterSeconds
整型
Creates a TTL index.
名称
字符串
唯一标识索引的名称。 默认情况下,MongoDB 会根据键创建索引名称。
部分过滤器表达式
数组|对象
Creates a partial index.
稀疏
布尔
创建稀疏索引。
unique
布尔
创建唯一索引。
命令选项
名称类型说明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 用于扩展级别的其他错误(例如连接错误)。
示例
创建复合索引
The following example creates a compound index on the borough and cuisine fields in the restaurants collection in the test database.
$collection = (new MongoDB\Client)->selectCollection('test', 'restaurants'); $indexName = $collection->createIndex(['borough' => 1, 'cuisine' => 1]); var_dump($indexName);
而输出将类似如下所示:
string(19) "borough_1_cuisine_1"
创建部分索引
The following example adds a partial index on the borough field in the restaurants collection in the test database. The partial index indexes only documents where the borough field exists.
$collection = (new MongoDB\Client)->selectCollection('test', 'restaurants'); $indexName = $collection->createIndex( ['borough' => 1], [ 'partialFilterExpression' => [ 'borough' => ['$exists' => true], ], ] ); var_dump($indexName);
而输出将类似如下所示:
string(9) "borough_1"
另请参阅
createIndexes command reference in the MongoDB manual
MongoDB 手册中的索引文档