"""Offline MongoDB covered query eligibility & projection verifier."""
import json
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
def evaluate_covered_query(docs, index_fields, query_filter, projection):
idx_set = set(index_fields)
is_multikey = any(
isinstance(d.get(f), list) for d in docs for f in index_fields
)
has_subdoc = any(
isinstance(d.get(f), dict) or "." in f for d in docs for f in index_fields
)
query_fields = set(query_filter.keys())
include_id = projection.get("_id", 1) != 0
returned_fields = {k for k, v in projection.items() if k != "_id" and v == 1}
if include_id:
returned_fields.add("_id")
covered = (
query_fields.issubset(idx_set)
and returned_fields.issubset(idx_set)
and not is_multikey
and not has_subdoc
)
# Execute actual projection on matching docs
matched = [
d for d in docs if all(d.get(k) == v for k, v in query_filter.items())
]
projected = [{f: d[f] for f in sorted(returned_fields) if f in d} for d in matched]
return {
"covered": covered,
"totalDocsExamined": 0 if covered else len(matched),
"totalKeysExamined": len(matched),
"stage": "PROJECTION_COVERED" if covered else "FETCH",
"results": projected,
}
def main():
users = [
{
"_id": "53402597d852426020000002",
"contact": "987654321",
"dob": "01-01-1991",
"gender": "M",
"name": "Tom Benzamin",
"user_name": "tombenzamin",
"tags": ["nosql", "db"],
"profile": {"tier": "gold"},
},
{
"_id": "53402597d852426020000003",
"contact": "123456789",
"dob": "05-06-1993",
"gender": "F",
"name": "Alice Lin",
"user_name": "alicelin",
"tags": ["cloud"],
"profile": {"tier": "silver"},
},
]
# Case 1: Covered query on compound index {gender: 1, user_name: 1} with _id: 0
r_covered = evaluate_covered_query(
users,
["gender", "user_name"],
{"gender": "M"},
{"user_name": 1, "_id": 0},
)
c1_actual = r_covered
c1_expected = {
"covered": True,
"totalDocsExamined": 0,
"totalKeysExamined": 1,
"stage": "PROJECTION_COVERED",
"results": [{"user_name": "tombenzamin"}],
}
# Case 2: Non-covered when _id is not excluded, or when index covers array/subdocument fields
r_with_id = evaluate_covered_query(
users,
["gender", "user_name"],
{"gender": "M"},
{"user_name": 1},
)
r_array = evaluate_covered_query(
users,
["tags"],
{"tags": "nosql"},
{"tags": 1, "_id": 0},
)
r_subdoc = evaluate_covered_query(
users,
["profile"],
{"profile": {"tier": "gold"}},
{"profile": 1, "_id": 0},
)
c2_actual = {
"with_default_id_covered": r_with_id["covered"],
"with_default_id_docs_examined": r_with_id["totalDocsExamined"],
"array_index_covered": r_array["covered"],
"subdoc_index_covered": r_subdoc["covered"],
}
c2_expected = {
"with_default_id_covered": False,
"with_default_id_docs_examined": 1,
"array_index_covered": False,
"subdoc_index_covered": False,
}
cases = [
{
"name": "covered_query_zero_doc_fetch",
"summary": "Verify compound index {gender: 1, user_name: 1} with {_id: 0, user_name: 1} achieves totalDocsExamined=0.",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "uncovered_default_id_array_and_subdoc",
"summary": "Verify omitting _id: 0 or indexing array/subdocument fields forces FETCH instead of covered scan.",
"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-covered-queries-lab/explore-covered-queries.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-covered-queries.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1736.zip
课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip