MongoDB 查询分析
系统梳理 MongoDB 查询性能诊断核心方法 explain() 与 hint(),对照早期 2.x 字段(cursor、indexOnly、nscanned)与现代 explain('executionStats') 阶段树(IXSCAN、COLLSCAN、FETCH、totalDocsExamined),并完成离线执行计划模拟验证。
学完这一章,你能够
- 系统梳理 MongoDB 查询性能诊断核心方法 explain() 与 hint(),对照早期 2.x 字段(cursor、indexOnly、nscanned)与现代 explain('executionStats') 阶段树(IXSCAN、COLLSCAN、FETCH、totalDocsExamined),并完成离线执行计划模拟验证。
使用 explain() 诊断索引命中与执行统计
查询分析用于检验所建索引是否真正生效、扫描代价是否合理,最常用的两个辅助方法是 `explain()` 与 `hint()`。在 `users` 集合建立 `{gender: 1, user_name: 1}` 索引(现代版本用 `createIndex()` 替代历史 `ensureIndex()`)后,对查询追加 `.explain()`(现代版本推荐 `.explain("executionStats")`)即可返回完整的查询计划与执行统计。
在理解输出指标时需兼顾历史版本与现代版本的字段对照:早期 2.x 输出的 `indexOnly: true`、`cursor: "BtreeCursor gender_1_user_name_1"`(未走索引时为 `BasicCursor`,索引定义曾记录于历史 `system.indexes` 集合)、`n`、`nscanned`/`nscannedObjects`、`millis` 及 `indexBounds`,在现代 MongoDB(3.0+ 至 8.x)的 `explain("executionStats")` 中分别对应执行阶段 `PROJECTION_COVERED` + `IXSCAN`(全表扫描为 `COLLSCAN`)、`nReturned`、`totalKeysExamined`/`totalDocsExamined`、`executionTimeMillis` 以及 `inputStage.indexBounds`。调优的核心目标是让扫描键数和扫描文档数尽量逼近返回文档数,并在覆盖查询时把 `totalDocsExamined` 降为 0。
使用 hint() 强制指定候选索引
尽管 MongoDB 查询优化器通常会通过多计划竞赛选出最优索引,但在多字段复杂查询或数据分布倾斜导致优化器选错索引时,可以链式调用 `.hint({gender: 1, user_name: 1})` 强制引擎采用指定索引执行查询,并继续拼接 `.explain("executionStats")` 对比强制前后的扫描成本。离线查询计划模拟器验证了覆盖查询命中 `IXSCAN`/`PROJECTION_COVERED`、非前缀字段退化为 `COLLSCAN`(扫描全部 4 条文档)以及 `hint()` 强制走 `gender_1_user_name_1` 的行为差异。
离线模拟 explain('executionStats') 阶段树、COLLSCAN 回退与 hint() 强制索引
"""Offline MongoDB explain('executionStats') & hint() query planner verifier."""
import json
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
def simulate_explain(docs, indexes, query_filter, projection=None, hint=None):
projection = projection or {}
chosen_index = None
if hint is not None:
if hint not in indexes:
raise ValueError(f"Hinted index {hint} not found")
chosen_index = hint
else:
for idx in indexes:
if idx and idx[0] in query_filter:
chosen_index = idx
break
matched = [d for d in docs if all(d.get(k) == v for k, v in query_filter.items())]
if chosen_index is None:
return {
"stage": "COLLSCAN",
"legacy_cursor": "BasicCursor",
"indexName": None,
"nReturned": len(matched),
"totalKeysExamined": 0,
"totalDocsExamined": len(docs),
"indexOnly": False,
}
idx_name = "_".join(f"{f}_1" for f in chosen_index)
include_id = projection.get("_id", 1) != 0
ret_fields = {k for k, v in projection.items() if k != "_id" and v == 1}
if include_id or not projection:
ret_fields.add("_id")
covered = set(query_filter.keys()).issubset(set(chosen_index)) and ret_fields.issubset(set(chosen_index))
return {
"stage": "PROJECTION_COVERED" if covered else "FETCH",
"inputStage": "IXSCAN",
"legacy_cursor": f"BtreeCursor {idx_name}",
"indexName": idx_name,
"nReturned": len(matched),
"totalKeysExamined": len(matched),
"totalDocsExamined": 0 if covered else len(matched),
"indexOnly": covered,
}
def main():
users = [
{"_id": 1, "gender": "M", "user_name": "tombenzamin", "age": 30},
{"_id": 2, "gender": "F", "user_name": "alicelin", "age": 26},
{"_id": 3, "gender": "F", "user_name": "carawang", "age": 29},
{"_id": 4, "gender": "F", "user_name": "evazhou", "age": 32},
]
indexes = [("gender", "user_name"), ("age",)]
# Case 1: explain() on covered compound index query (IXSCAN + PROJECTION_COVERED)
exp_cov = simulate_explain(users, indexes, {"gender": "M"}, {"user_name": 1, "_id": 0})
c1_actual = exp_cov
c1_expected = {
"stage": "PROJECTION_COVERED",
"inputStage": "IXSCAN",
"legacy_cursor": "BtreeCursor gender_1_user_name_1",
"indexName": "gender_1_user_name_1",
"nReturned": 1,
"totalKeysExamined": 1,
"totalDocsExamined": 0,
"indexOnly": True,
}
# Case 2: COLLSCAN without matching index vs hint() forcing specific index
exp_scan = simulate_explain(users, indexes, {"user_name": "tombenzamin"})
exp_hint = simulate_explain(
users,
indexes,
{"gender": "M", "age": 30},
{"user_name": 1, "_id": 0},
hint=("gender", "user_name"),
)
c2_actual = {
"unindexed_stage": exp_scan["stage"],
"unindexed_docs_examined": exp_scan["totalDocsExamined"],
"hinted_index": exp_hint["indexName"],
"hinted_input_stage": exp_hint["inputStage"],
"hinted_returned": exp_hint["nReturned"],
}
c2_expected = {
"unindexed_stage": "COLLSCAN",
"unindexed_docs_examined": 4,
"hinted_index": "gender_1_user_name_1",
"hinted_input_stage": "IXSCAN",
"hinted_returned": 1,
}
cases = [
{
"name": "explain_covered_ixscan_stats",
"summary": "Verify explain() reports IXSCAN/PROJECTION_COVERED, indexOnly=true, and totalDocsExamined=0.",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "collscan_vs_hint_forced_index",
"summary": "Verify non-prefix filter falls back to COLLSCAN while hint() forces the specified compound index.",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 在离线计划模拟器中确认覆盖查询返回 PROJECTION_COVERED/IXSCAN 且 totalDocsExamined=0,无前缀索引回退为 COLLSCAN,hint() 强制选用目标复合索引。
所需环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。
当前源码 SHA256:ff0f06857e284700c4a1d208b08ee2423622d763d3edd7cf7dccade3e771ae54
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。
ZIP SHA256:a6cd29b28ac5d2cac82f8a87dcf33717cfd6b13fc3178f97230c8656f6d99144
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在现代 MongoDB 的 explain('executionStats') 输出中,如何一眼判断一条查询是否触发了全集合扫描或实现了覆盖索引?
展开参考解答
查看 winningPlan 阶段树:出现 COLLSCAN 表示全集合扫描;出现 IXSCAN 且外层为 PROJECTION_COVERED 同时 executionStats.totalDocsExamined 为 0 表示触发了覆盖索引查询。