"""Offline MongoDB MapReduce vs modern Aggregation Pipeline equivalence verifier."""
from collections import defaultdict
import json
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
def run_map_reduce(docs, query_fn, map_fn, reduce_fn, out_name):
filtered = [d for d in docs if query_fn(d)]
grouped = defaultdict(list)
emit_count = 0
for doc in filtered:
for k, v in map_fn(doc):
grouped[k].append(v)
emit_count += 1
reduce_calls = 0
results = []
for k in sorted(grouped.keys()):
vals = grouped[k]
if len(vals) > 1:
reduce_calls += 1
reduced = reduce_fn(k, vals)
else:
reduced = vals[0]
results.append({"_id": k, "value": reduced})
return {
"result": out_name,
"counts": {
"input": len(filtered),
"emit": emit_count,
"reduce": reduce_calls,
"output": len(results),
},
"ok": 1,
"docs": results,
}
def run_modern_aggregation(docs, status_filter, group_field, sum_field=None):
totals = defaultdict(int)
for d in docs:
if d.get("status") == status_filter:
totals[d[group_field]] += 1 if sum_field is None else d[sum_field]
return [{"_id": k, "value": totals[k]} for k in sorted(totals.keys())]
def main():
# Case 1: posts collection active article count per user_name (MapReduce stats + output)
posts = [
{"post_text": "Tech docs", "user_name": "mark", "status": "active"},
{"post_text": "Tech docs", "user_name": "mark", "status": "active"},
{"post_text": "Tech docs", "user_name": "mark", "status": "active"},
{"post_text": "Tech docs", "user_name": "mark", "status": "active"},
{"post_text": "Tech docs", "user_name": "mark", "status": "disabled"},
{"post_text": "Tech docs", "user_name": "alex", "status": "disabled"},
{"post_text": "Tech docs", "user_name": "alex", "status": "disabled"},
{"post_text": "Tech docs", "user_name": "alex", "status": "active"},
]
mr_posts = run_map_reduce(
posts,
query_fn=lambda d: d["status"] == "active",
map_fn=lambda d: [(d["user_name"], 1)],
reduce_fn=lambda k, vals: sum(vals),
out_name="post_total",
)
c1_actual = {
"result": mr_posts["result"],
"counts": mr_posts["counts"],
"docs": mr_posts["docs"],
}
c1_expected = {
"result": "post_total",
"counts": {"input": 5, "emit": 5, "reduce": 1, "output": 2},
"docs": [
{"_id": "alex", "value": 1},
{"_id": "mark", "value": 4},
],
}
# Case 2: orders collection (status: "A", group by cust_id, sum amount) MapReduce vs Aggregation Pipeline
orders = [
{"cust_id": "A123", "amount": 500, "status": "A"},
{"cust_id": "A123", "amount": 250, "status": "A"},
{"cust_id": "B212", "amount": 200, "status": "A"},
{"cust_id": "A123", "amount": 300, "status": "D"},
]
mr_orders = run_map_reduce(
orders,
query_fn=lambda d: d["status"] == "A",
map_fn=lambda d: [(d["cust_id"], d["amount"])],
reduce_fn=lambda k, vals: sum(vals),
out_name="order_totals",
)
agg_orders = run_modern_aggregation(orders, status_filter="A", group_field="cust_id", sum_field="amount")
agg_posts = run_modern_aggregation(posts, status_filter="active", group_field="user_name")
c2_actual = {
"orders_mr": mr_orders["docs"],
"orders_agg_matches_mr": agg_orders == mr_orders["docs"],
"posts_agg_matches_mr": agg_posts == mr_posts["docs"],
"deprecated_in_mongodb_5_0": True,
}
c2_expected = {
"orders_mr": [
{"_id": "A123", "value": 750},
{"_id": "B212", "value": 200},
],
"orders_agg_matches_mr": True,
"posts_agg_matches_mr": True,
"deprecated_in_mongodb_5_0": True,
}
cases = [
{
"name": "mapreduce_posts_counts_and_output",
"summary": "Verify MapReduce query/map/reduce counts (input=5, emit=5, reduce=1, output=2) and grouped totals.",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "mapreduce_vs_modern_aggregation_pipeline",
"summary": "Verify modern $match + $group Aggregation Pipeline produces identical results to deprecated MapReduce.",
"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-map-reduce-lab/explore-map-reduce.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-map-reduce.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1752.zip
课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip