"""Offline MongoDB aggregation pipeline verifier (no live mongod required)."""
from collections import defaultdict
import json
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
def eval_match(doc, cond):
for field, rule in cond.items():
val = doc.get(field)
if isinstance(rule, dict):
for op, target in rule.items():
if op == "$gt" and not (val is not None and val > target):
return False
if op == "$gte" and not (val is not None and val >= target):
return False
if op == "$lt" and not (val is not None and val < target):
return False
if op == "$lte" and not (val is not None and val <= target):
return False
if op == "$eq" and val != target:
return False
elif val != rule:
return False
return True
def eval_expr(doc, expr):
if isinstance(expr, str) and expr.startswith("$"):
return doc.get(expr[1:])
return expr
def run_pipeline(docs, pipeline):
current = [dict(d) for d in docs]
for stage in pipeline:
(op, spec), = stage.items()
if op == "$match":
current = [d for d in current if eval_match(d, spec)]
elif op == "$project":
include_id = spec.get("_id", 1) != 0
out = []
for d in current:
row = {}
if include_id and "_id" in d:
row["_id"] = d["_id"]
for k, v in spec.items():
if k == "_id":
continue
if v == 1 and k in d:
row[k] = d[k]
out.append(row)
current = out
elif op == "$unwind":
field = spec[1:] if spec.startswith("$") else spec
out = []
for d in current:
arr = d.get(field, [])
if isinstance(arr, list):
for item in arr:
copy_doc = dict(d)
copy_doc[field] = item
out.append(copy_doc)
current = out
elif op == "$group":
key_expr = spec["_id"]
groups = defaultdict(list)
order = []
for d in current:
gk = None if key_expr is None else eval_expr(d, key_expr)
if gk not in groups:
order.append(gk)
groups[gk].append(d)
out = []
for gk in order:
items = groups[gk]
row = {"_id": gk}
for out_field, acc in spec.items():
if out_field == "_id":
continue
(acc_op, acc_arg), = acc.items()
vals = [eval_expr(x, acc_arg) for x in items]
if acc_op == "$sum":
row[out_field] = sum(vals)
elif acc_op == "$avg":
row[out_field] = sum(vals) / len(vals)
elif acc_op == "$min":
row[out_field] = min(vals)
elif acc_op == "$max":
row[out_field] = max(vals)
elif acc_op == "$push":
row[out_field] = list(vals)
elif acc_op == "$addToSet":
seen = []
for v in vals:
if v not in seen:
seen.append(v)
row[out_field] = seen
elif acc_op == "$first":
row[out_field] = vals[0]
elif acc_op == "$last":
row[out_field] = vals[-1]
out.append(row)
current = out
elif op == "$sort":
for field, direction in reversed(list(spec.items())):
current.sort(key=lambda d, f=field: d.get(f), reverse=(direction == -1))
elif op == "$skip":
current = current[spec:]
elif op == "$limit":
current = current[:spec]
else:
raise ValueError(f"Unsupported stage: {op}")
return current
def main():
mycol = [
{
"_id": "7df78ad8902c",
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by_user": "devdocs.example",
"url": "https://devdocs.example/mongodb",
"tags": ["mongodb", "database", "NoSQL"],
"likes": 100,
},
{
"_id": "7df78ad8902d",
"title": "NoSQL Overview",
"description": "No sql database is very fast",
"by_user": "devdocs.example",
"url": "https://devdocs.example/mongodb",
"tags": ["mongodb", "database", "NoSQL"],
"likes": 10,
},
{
"_id": "7df78ad8902e",
"title": "Neo4j Overview",
"description": "Neo4j is no sql database",
"by_user": "Neo4j",
"url": "https://neo4j.example/docs",
"tags": ["neo4j", "database", "NoSQL"],
"likes": 750,
},
]
# Case 1: $group count per by_user (SQL GROUP BY equivalent)
c1_actual = run_pipeline(
mycol,
[
{"$group": {"_id": "$by_user", "num_tutorial": {"$sum": 1}}},
{"$sort": {"_id": 1}},
],
)
c1_expected = [
{"_id": "Neo4j", "num_tutorial": 1},
{"_id": "devdocs.example", "num_tutorial": 2},
]
# Case 2: All 8 group accumulators ($sum, $avg, $min, $max, $push, $addToSet, $first, $last)
acc_docs = [
{"by_user": "devdocs.example", "likes": 100, "url": "https://devdocs.example/a"},
{"by_user": "devdocs.example", "likes": 10, "url": "https://devdocs.example/a"},
{"by_user": "devdocs.example", "likes": 40, "url": "https://devdocs.example/b"},
]
c2_actual = run_pipeline(
acc_docs,
[
{
"$group": {
"_id": "$by_user",
"sum_likes": {"$sum": "$likes"},
"avg_likes": {"$avg": "$likes"},
"min_likes": {"$min": "$likes"},
"max_likes": {"$max": "$likes"},
"pushed_urls": {"$push": "$url"},
"unique_urls": {"$addToSet": "$url"},
"first_url": {"$first": "$url"},
"last_url": {"$last": "$url"},
}
}
],
)[0]
c2_expected = {
"_id": "devdocs.example",
"sum_likes": 150,
"avg_likes": 50.0,
"min_likes": 10,
"max_likes": 100,
"pushed_urls": [
"https://devdocs.example/a",
"https://devdocs.example/a",
"https://devdocs.example/b",
],
"unique_urls": [
"https://devdocs.example/a",
"https://devdocs.example/b",
],
"first_url": "https://devdocs.example/a",
"last_url": "https://devdocs.example/b",
}
# Case 3: $project with default _id and explicit _id: 0
articles = [
{"_id": 1, "title": "Intro", "author": "Alice", "score": 65},
{"_id": 2, "title": "Pipelines", "author": "Bob", "score": 78},
{"_id": 3, "title": "Indexes", "author": "Cara", "score": 90},
{"_id": 4, "title": "Sharding", "author": "Dan", "score": 95},
{"_id": 5, "title": "GridFS", "author": "Eva", "score": 82},
{"_id": 6, "title": "Capped", "author": "Fay", "score": 71},
]
with_id = run_pipeline(articles[:1], [{"$project": {"title": 1, "author": 1}}])[0]
without_id = run_pipeline(articles[:1], [{"$project": {"_id": 0, "title": 1, "author": 1}}])[0]
c3_actual = {"with_id_keys": sorted(with_id.keys()), "without_id": without_id}
c3_expected = {
"with_id_keys": ["_id", "author", "title"],
"without_id": {"title": "Intro", "author": "Alice"},
}
# Case 4: $match (70 < score <= 90) -> $group count, plus $skip & $limit & $unwind
matched_count = run_pipeline(
articles,
[
{"$match": {"score": {"$gt": 70, "$lte": 90}}},
{"$group": {"_id": None, "count": {"$sum": 1}}},
],
)[0]["count"]
skipped_titles = [
d["title"]
for d in run_pipeline(articles, [{"$skip": 5}, {"$limit": 2}])
]
unwound_tags = len(run_pipeline(mycol[:1], [{"$unwind": "$tags"}]))
c4_actual = {
"matched_70_to_90": matched_count,
"after_skip_5": skipped_titles,
"unwound_tag_docs": unwound_tags,
}
c4_expected = {
"matched_70_to_90": 4,
"after_skip_5": ["Capped"],
"unwound_tag_docs": 3,
}
cases = [
{
"name": "group_by_user_count",
"summary": "Verify $group + $sum: 1 counts documents per author like SQL GROUP BY.",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "group_accumulators_all_eight",
"summary": "Verify $sum, $avg, $min, $max, $push, $addToSet, $first, and $last accumulators.",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "project_include_and_exclude_id",
"summary": "Verify $project keeps _id by default and omits _id when _id: 0 is specified.",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
{
"name": "match_skip_limit_unwind_pipeline",
"summary": "Verify chained $match (70 < score <= 90) + $group, $skip: 5, $limit, and $unwind.",
"expected": c4_expected,
"actual": c4_actual,
"passed": c4_actual == c4_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-aggregate-lab/explore-aggregate.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-aggregate.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1729.zip
课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip