"""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()
本例需在 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。
入口文件:projects/mongodb-analyzing-queries-lab/explore-analyzing-queries.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-analyzing-queries.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1730.zip
课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip