定义
$indexStats返回集合中每个索引使用情况的统计信息。如果在运行时存在访问控制,请至少以具有
clusterMonitor角色的用户身份进行验证。$indexStats阶段采用一个空文档,其语法如下:{ $indexStats: { } }对于每个索引,返回文档包含以下字段:
输出字段说明name索引名称。
索引密钥规范。
另请参阅:规范。
mongod进程的主机名和端口。相关托管的索引使用指标,包括:
since:MongoDB 收集统计数据的时间
警告:
accesses字段仅报告查询运行所在节点的索引使用指标。获取更全面的索引使用统计信息,请在集群中的每个节点上运行$indexStats。与主机关联的分片的名称
仅适用于分片群集。
索引的完整规范文档,其中包括索引键和索引属性。
仅当值为
true时才包含索引选项hidden。指示索引当前是否正在构建。
仅当
true时才可用。
行为
Accesses 字段
accesses字段报告的统计信息仅应用于正在运行查询的节点,并且仅包括由用户请求驱动的索引访问权限。 accesses字段不包括以下内部操作:
数据段分割和迁移操作
通过复制进行索引访问权限,例如oplog应用程序和初始同步期间的索引构建
限制
$indexStats必须是聚合管道的第一阶段。$indexStats不允许在事务中使用。
索引统计数据重置注意事项
示例
以下示例使用 sample_mflix 示例数据集中的 movies 集合。有关如何将此数据集加载到部署中的详细信息,请参阅 加载示例数据集。
在 movies集合上创建以下索引:
db.movies.createIndex( { year: 1, title: 1 } )db.movies.createIndex( { rated: 1, year: 1 } )db.movies.createIndex( { metacritic: 1 }, { partialFilterExpression: { rated: "R" } })对集合运行一些查询:
db.movies.find( { rated: "R" } )db.movies.find( { year: 1994 } ).sort( { title: 1 } )db.movies.find( { metacritic: { $gt: 90 } } )以下聚合操作返回一个文档,其中包含 movies集合上每个索引的使用情况统计信息:
db.movies.aggregate( [ { $indexStats: { } } ] )[ { name: 'year_1_title_1', key: { year: 1, title: 1 }, host: ..., accesses: ..., spec: { v: 2, key: { year: 1, title: 1 }, name: 'year_1_title_1' } }, { name: 'rated_1_year_1', key: { rated: 1, year: 1 }, host: ..., accesses: ..., spec: { v: 2, key: { rated: 1, year: 1 }, name: 'rated_1_year_1' } }, { name: 'metacritic_1', key: { metacritic: 1 }, host: ..., accesses: ..., spec: { v: 2, key: { metacritic: 1 }, name: 'metacritic_1', partialFilterExpression: { rated: 'R' } } }, { name: '_id_', key: { _id: 1 }, host: ..., accesses: ..., spec: { v: 2, key: { _id: 1 }, name: '_id_' } }, { name: 'cast_text_fullplot_text_genres_text_title_text', key: { _fts: 'text', _ftsx: 1 }, host: ..., accesses: ..., spec: ... }]要使用MongoDB Node.js驱动程序将 $indexStats 阶段添加到聚合管道,请在管道对象中使用 $indexStats操作符。
以下示例创建了一个管道阶段,该阶段返回一个文档,其中包含集合上每个索引的使用情况统计信息。然后,该示例运行聚合管道:
const pipeline = [{ $indexStats: {} }];
const cursor = collection.aggregate(pipeline);return cursor;