Appearance
MongoDB 查询分析
explain 查看执行计划
在 find、aggregate 等后加 .explain() 可查看执行计划:
javascript
db.users.find({ age: { $gt: 25 } }).explain("executionStats")关注:
- stage:IXSCAN 表示使用索引,COLLSCAN 表示全表扫描。
- executionStats:
totalDocsExamined、totalKeysExamined、executionTimeMillis等。 - winningPlan:优化器选择的计划。
explain("allPlansExecution") 可看到被拒绝的其它计划,便于对比。
索引是否被使用
若 stage 为 COLLSCAN,说明未使用索引或没有合适索引,应考虑为查询条件/排序建索引。
Profiler 慢查询
在 mongod 配置中开启 profiler:
yaml
operationProfiling:
mode: slowOp
slowOpThresholdMs: 100慢操作会写入 system.profile 集合,可查询分析:
javascript
db.system.profile.find().sort({ ts: -1 }).limit(10)可看到命令、耗时、计划等,便于定位慢查询并优化索引或写法。下一节介绍 MongoDB 原子操作。