db.collection.explain()
查询执行计划分析
语法
db.collection.find(<query>).explain(<verbosity>)说明
explain 返回查询的执行计划信息,包括扫描方式(IXSCAN/COLLSCAN)、使用的索引、扫描的文档数和返回的文档数等。是查询性能调优的核心工具。
参数
"queryPlanner"默认,仅返回查询计划(不执行)
"executionStats"返回查询计划和执行统计
"allPlansExecution"返回所有候选计划的执行统计
示例
查看查询计划
分析查询使用哪个索引
db.users.find({ email: "user@example.com" }).explain("executionStats")检查全表扫描
winningPlan 中 stage 为 COLLSCAN 表示需要加索引
db.orders.find({ createdAt: { $gte: lastWeek } }).explain()