"""Offline MongoDB find/findOne, projection, $and/$or, regex & cursor chain verifier (Ch19 query)."""
import copy
import json
import re
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
def eval_filter(doc: dict, flt: dict) -> bool:
for k, cond in flt.items():
if k == "$and":
if not all(eval_filter(doc, sub) for sub in cond):
return False
elif k == "$or":
if not any(eval_filter(doc, sub) for sub in cond):
return False
else:
val = doc.get(k)
if isinstance(cond, dict):
for op, target in cond.items():
if op == "$gt" and not (isinstance(val, (int, float)) and val > target):
return False
elif op == "$gte" and not (isinstance(val, (int, float)) and val >= target):
return False
elif op == "$lt" and not (isinstance(val, (int, float)) and val < target):
return False
elif op == "$lte" and not (isinstance(val, (int, float)) and val <= target):
return False
elif op == "$eq" and val != target:
return False
elif op == "$ne" and val == target:
return False
elif op == "$regex" and not (isinstance(val, str) and re.search(target, val)):
return False
else:
if val != cond:
return False
return True
def apply_projection(doc: dict, proj: dict | None) -> dict:
if not proj:
return copy.deepcopy(doc)
non_id = {k: v for k, v in proj.items() if k != "_id"}
inclusion = any(v == 1 for v in non_id.values())
if inclusion:
out = {}
if proj.get("_id", 1) != 0 and "_id" in doc:
out["_id"] = doc["_id"]
for k, v in non_id.items():
if v == 1 and k in doc:
out[k] = copy.deepcopy(doc[k])
return out
out = copy.deepcopy(doc)
for k, v in proj.items():
if v == 0:
out.pop(k, None)
return out
USERS = [
{"_id": 1, "name": "Alice", "age": 28, "city": "New York"},
{"_id": 2, "name": "Aaron", "age": 34, "city": "New York"},
{"_id": 3, "name": "Bob", "age": 22, "city": "Chicago"},
{"_id": 4, "name": "Amy", "age": 31, "city": "New York"},
{"_id": 5, "name": "Carol", "age": 26, "city": "Boston"},
]
ARTICLES = [
{"_id": 101, "title": "MongoDB 教程", "by": "蓝色天空网", "likes": 100},
{"_id": 102, "title": "Python 教程", "by": "蓝色天空网", "likes": 50},
{"_id": 103, "title": "SQL 教程", "by": "其他作者", "likes": 30},
{"_id": 104, "title": "MongoDB 教程", "by": "社区投稿", "likes": 80},
]
def find(docs, flt=None, proj=None, sort_spec=None, skip=0, limit=0):
res = [d for d in docs if eval_filter(d, flt or {})]
if sort_spec:
for field, direction in reversed(sort_spec):
res.sort(key=lambda d: d[field], reverse=(direction == -1))
if skip:
res = res[skip:]
if limit:
res = res[:limit]
return [apply_projection(d, proj) for d in res]
def case_find_and_find_one_with_projection():
all_cnt = len(find(USERS))
gt25_proj = find(USERS, {"age": {"$gt": 25}}, {"name": 1, "age": 1, "_id": 0})
one_alice = find(USERS, {"name": "Alice"}, {"name": 1, "age": 1, "_id": 0}, limit=1)[0]
actual = {
"all_count": all_cnt,
"gt25_names": [d["name"] for d in gt25_proj],
"id_excluded": all("_id" not in d for d in gt25_proj),
"find_one_alice": one_alice,
}
expected = {
"all_count": 5,
"gt25_names": ["Alice", "Aaron", "Amy", "Carol"],
"id_excluded": True,
"find_one_alice": {"name": "Alice", "age": 28},
}
return {
"name": "find_and_find_one_with_projection",
"summary": "验证 find()、findOne() 与投影 {name: 1, age: 1, _id: 0} 的字段裁剪结果。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_comparison_and_rdbms_where_equivalence():
actual = {
"eq": [d["_id"] for d in find(ARTICLES, {"by": "蓝色天空网"})],
"lt50": [d["_id"] for d in find(ARTICLES, {"likes": {"$lt": 50}})],
"lte50": [d["_id"] for d in find(ARTICLES, {"likes": {"$lte": 50}})],
"gt50": [d["_id"] for d in find(ARTICLES, {"likes": {"$gt": 50}})],
"gte50": [d["_id"] for d in find(ARTICLES, {"likes": {"$gte": 50}})],
"ne50": [d["_id"] for d in find(ARTICLES, {"likes": {"$ne": 50}})],
}
expected = {
"eq": [101, 102],
"lt50": [103],
"lte50": [102, 103],
"gt50": [101, 104],
"gte50": [101, 102, 104],
"ne50": [101, 103, 104],
}
return {
"name": "comparison_and_rdbms_where_equivalence",
"summary": "验证等于、$lt、$lte、$gt、$gte、$ne 六类条件查询与 SQL WHERE 子句等价。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_and_or_combined_logic():
implicit_and = [d["_id"] for d in find(ARTICLES, {"by": "蓝色天空网", "title": "MongoDB 教程"})]
or_query = [d["_id"] for d in find(ARTICLES, {"$or": [{"by": "蓝色天空网"}, {"title": "MongoDB 教程"}]})]
combined = [
d["_id"]
for d in find(
ARTICLES,
{"likes": {"$gt": 50}, "$or": [{"by": "蓝色天空网"}, {"title": "MongoDB 教程"}]},
)
]
actual = {"implicit_and": implicit_and, "or_query": or_query, "and_or_combined": combined}
expected = {"implicit_and": [101], "or_query": [101, 102, 104], "and_or_combined": [101, 104]}
return {
"name": "and_or_combined_logic",
"summary": "验证逗号隐式 AND、$or 以及 likes>50 AND (by=... OR title=...) 联合逻辑过滤。",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_regex_query_matching():
matched = [d["name"] for d in find(USERS, {"name": {"$regex": r"^A"}})]
expected = ["Alice", "Aaron", "Amy"]
return {
"name": "regex_query_matching",
"summary": "验证正则表达式 /^A/ 匹配所有以字母 A 开头的 name 字段。",
"expected": expected,
"actual": matched,
"passed": matched == expected,
}
def case_chained_sort_skip_limit_pipeline():
res = find(
USERS,
{"$and": [{"age": {"$gt": 25}}, {"city": "New York"}]},
{"name": 1, "age": 1, "_id": 0},
sort_spec=[("age", -1)],
skip=1,
limit=2,
)
expected = [{"name": "Amy", "age": 31}, {"name": "Alice", "age": 28}]
return {
"name": "chained_sort_skip_limit_pipeline",
"summary": "验证组合查询:$and 过滤 + 投影 + 按 age 降序 + skip(1).limit(2) 分页链式执行。",
"expected": expected,
"actual": res,
"passed": res == expected,
}
def main():
cases = [
case_find_and_find_one_with_projection(),
case_comparison_and_rdbms_where_equivalence(),
case_and_or_combined_logic(),
case_regex_query_matching(),
case_chained_sort_skip_limit_pipeline(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/mongodb-query-lab/explore-query.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-query.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1763.zip