定义
listIndexes返回指定集合上的索引信息,包括隐藏索引和当前正在构建的索引。返回的索引信息包括用于创建索引的键和选项。 您可以选择设立第批处理结果的批处理大小。
提示
In
mongosh, this command can also be run through thedb.collection.getIndexes()helper method.Helper methods are convenient for
mongoshusers, but they may not return the same level of information as database commands. In cases where the convenience is not needed or the additional return fields are required, use the database command.
兼容性
此命令可用于以下环境中托管的部署:
- MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务
注意
所有 MongoDB Atlas 集群都支持此命令。有关 Atlas 对所有命令的支持的信息,请参阅不支持的命令。
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
语法
该命令具有以下语法:
db.runCommand ( { listIndexes: "<collection-name>", cursor: { batchSize: <int> }, comment: <any> } )
命令字段
该命令接受以下字段:
字段 | 类型 | 说明 |
|---|---|---|
| 字符串 | 集合的名称。 |
| 整型 | 可选。指定游标批处理大小。 |
| any | 可选。用户提供的待附加到该命令的注释。设置后,该注释将与该命令的记录一起出现在以下位置:
注释可以是任何有效的 BSON 类型(字符串、整型、对象、数组等)。 在 |
必需的访问权限
If access control is enforced, the built-in read role provides the required privileges to run listIndexes for the collections in a database.
行为
Atlas Search 索引
listIndexes does not return information on Atlas Search indexes. Instead, use $listSearchIndexes.
客户端断开连接
If the client that issued listIndexes disconnects before the operation completes, MongoDB marks listIndexes for termination using killOp.
副本集节点状态限制
To run on a replica set member, listIndexes operations require the member to be in PRIMARY or SECONDARY state. If the member is in another state, such as STARTUP2, the operation errors.
通配符索引 (Wildcard Indexes)
从 MongoDB 6.3、6.0.5 和 5.0.16 开始,wildcardProjection 字段以其提交的形式存储索引投影。早期版本的服务器可能已将投影以标准化形式存储。
The server uses the index the same way, but you may notice a difference in the output of the listIndexes and db.collection.getIndexes() commands.
输出
listIndexes.cursor中游标指定的批处理大小返回结果集。批处理输出中的每个文档都包含以下字段:
字段类型说明id
整型
:64位整型。如果为零,则不再有批量信息。如果非零,则为游标 ID,可在
getMore命令中使用以获取下一批索引信息。ns
字符串
数据库和集合名称采用以下格式:
<database-name>.<collection-name>firstBatch
文档
索引信息包括用于创建索引的键和选项。仅当值为 true 时,隐藏的索引选项才会显示。
根据需要使用
getMore检索其他结果。
示例
列出数据库索引
此示例列出 contacts 集合的索引,但未指定游标批处理大小。
1 db.runCommand ( 2 { 3 listIndexes: "contacts" 4 } 5 )
1 { 2 cursor: { 3 id: Long("0"), 4 ns: 'test.contacts', 5 firstBatch: [ 6 { v: 2, key: { _id: 1 }, name: '_id_', ns: 'test.contacts' }, 7 { v: 2, key: { a: 1 }, name: 'a_1', ns: 'test.contacts' } 8 ] 9 }, 10 ok: 1 11 }
指定结果批量大小
此示例列出 contacts 集合的索引,并指定游标批处理大小为 1。
1 db.runCommand ( 2 { 3 listIndexes: "contacts", cursor: { batchSize: 1 } 4 } 5 )
1 { 2 cursor: { 3 id: Long("4809221676960028307"), 4 ns: 'test.contacts', 5 firstBatch: [ { v: 2, key: { _id: 1 }, name: '_id_', ns: 'test.contacts' } ] 6 }, 7 ok: 1 8 }
检索其他结果
此示例使用 getMore 从 contacts 集合中检索更多结果批次。
1 db.runCommand( 2 { 3 getMore: Long("4809221676960028307"), collection: "contacts" 4 } 5 )
1 { 2 cursor: { 3 nextBatch: [ { v: 2, key: { a: 1 }, name: 'a_1', ns: 'test.contacts' } ], 4 id: Long("0"), 5 ns: 'test.contacts' 6 }, 7 ok: 1 8 }