MongoDB 5.0 中索引驻留内存需通过 WiredTiger cache 间接判断:查 serverStatus.wiredTiger.cache 的当前用量、读入总量和驱逐次数;结合集合 stats 的 indexSize 与 cache 占比、wt_stats 页面请求/读入比,以及慢查询执行时间波动和文档检查量,综合推断索引页是否稳定驻留。

要确认 MongoDB 5.0 中某个索引是否常驻物理内存、避免频繁从磁盘加载页,必须绕过“索引本身不占内存”的常见误解——WiredTiger 引擎将索引数据作为 B-tree 页面存于 cache 中,其驻留比例取决于工作集热度与 cache 压力,无法直接查“索引A占cache的X%”,但可通过间接指标精准推断。
确认 WiredTiger Cache 当前使用状态
第一步:连接到目标数据库(需 admin 权限),执行:
db.runCommand({ "serverStatus": 1 }).wiredTiger.cache
重点关注三项:
• 【bytes currently in the cache】:当前缓存总字节数,是计算比例的分母;
• 【bytes read into cache】:自启动以来累计读入 cache 的字节数,若该值远大于前者,说明大量页面被驱逐又重载;
• 【pages evicted by application threads】:应用线程主动驱逐页次数,持续非零表明 cache 不足,索引页难以稳定驻留。
若 bytes currently in the cache 长期低于 cacheSizeGB 配置值的 70%,索引驻留率必然偏低。
定位特定索引对应的数据页访问热度
方法一:用 db.collection.stats() 查索引所在集合的总体内存压力
db.getCollection("orders").stats({ scale: 1 })
提取 indexCount、indexSize 字段,并对比 wiredTiger.cache 中的 bytes currently in the cache。若 indexSize 占 bytes currently in the cache 比例 100,则索引页大概率未全部驻留。
方法二:启用详细统计并抓取索引页访问行为(需重启 mongod 启用)
在 mongod.conf 中添加:
wiredTiger:
engineConfig:
configString: "statistics=(all),statistics_log_path=wt_stats"
重启后等待 5 分钟,查看 data/wt_stats 文件中类似 cache: pages read into cache 和 cache: pages requested from the cache 的增量比——若后者远高于前者,说明索引页反复被请求却未长期保留在 cache 中。
通过慢查询反推索引驻留失效
第一步:开启 profiler 记录慢操作
db.setProfilingLevel(1, { slowms: 50 })
第二步:运行典型索引查询(如 db.orders.find({ status: "shipped" }).explain("executionStats"))
第三步:检查 executionStats 中的 totalDocsExamined 与 nReturned 是否接近,同时观察 executionTimeMillis 是否波动剧烈(如 8ms → 142ms → 12ms)。
若波动显著且无锁争用,基本可判定索引页被踢出 cache 后又重新加载。
注意:【explain("executionStats") 必须在 profiler 开启后执行,否则 totalDocsExamined 可能为 0】











