MongoDB Map Reduce
系统梳理 MongoDB Map-Reduce 计算模型的 map/emit/reduce 参数契约、counts 统计指标与 posts/orders 分组示例,并明确说明其在 MongoDB 5.0+ 已废弃及向现代 Aggregation Pipeline 迁移的等价实测。
学完这一章,你能够
- 系统梳理 MongoDB Map-Reduce 计算模型的 map/emit/reduce 参数契约、counts 统计指标与 posts/orders 分组示例,并明确说明其在 MongoDB 5.0+ 已废弃及向现代 Aggregation Pipeline 迁移的等价实测。
Map-Reduce 模型原理、命令语法与核心参数
Map-Reduce 是一种“先分治映射(Map)、再归约汇总(Reduce)”的批处理计算范式。在 MongoDB 中,`db.collection.mapReduce(map, reduce, options)` 通过自定义 `map` 函数遍历文档并调用 `emit(key, value)` 发射键值对,再将相同 `key` 的值序列交给 `reduce(key, values)` 归约为单一结果。需要特别提醒的是:自 **MongoDB 5.0 起官方已正式废弃 `mapReduce`**,推荐全面迁移至原生 C++ 执行、性能显著更高的聚合管道(`$match` + `$group` + `$merge`/`$out`),本节保留其原理与迁移对照以便维护旧系统。
`mapReduce` 的六个关键配置项分别为:`map`(发射键值对的映射函数)、`reduce`(将同一键的 `values` 数组合并为单值的归约函数,需满足幂等与结合律)、`out`(指定结果写入的目标集合或输出模式,不持久化时可在连接断开后自动清理临时集合)、`query`(在进入 `map` 之前先过滤文档的查询条件)、`sort`(发送给 `map` 前的预排序,常与 `limit` 搭配以减少归约开销)以及 `limit`(送入 `map` 的最大文档上限)。例如在 `orders` 集合中可先按 `status: "A"` 过滤,再按 `cust_id` 分组累加 `amount`。
posts 分组实战、输出统计字段与聚合管道等价迁移
以包含 8 篇用户文章的 `posts` 集合为例(`mark` 有 4 篇 `active` 与 1 篇 `disabled`,`alex` 有 1 篇 `active` 与 2 篇 `disabled`):设置 `query: {status: "active"}`、`map` 发射 `(this.user_name, 1)`、`reduce` 调用 `Array.sum(values)` 并输出到 `post_total` 集合后,统计结果显示共有 5 条文档进入 `map`、发射 5 次键值对,仅对多值键 `mark` 调用 1 次 `reduce`,最终产出 2 条分组结果文档。
返回摘要字段含义清晰:`result` 为存放输出结果的集合名;`timeMillis` 为执行耗时毫秒数;`counts.input` 为满足过滤条件送入 `map` 的文档数;`counts.emit` 为 `emit()` 总调用次数;`counts.output` 为结果集合中的文档总数;`ok: 1` 表示执行成功(异常时返回错误信息)。随后查询 `db.post_total.find()` 即可读取 `{_id: "mark", value: 4}` 与 `{_id: "alex", value: 1}`。虽然 `mapReduce` 借助 JavaScript 表达力很强,但受单线程 JS 引擎开销制约;离线脚本已验证用现代聚合管道 `[$match, $group]` 在 `posts` 与 `orders` 两个场景下均可得到字节级一致的结果。
离线验证 MapReduce counts(5/5/1/2) 统计及与现代聚合管道结果一致性
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
改写为 db.posts.aggregate([{$match: {status: 'active'}}, {$group: {_id: '$user_name', value: {$sum: 1}}}, {$out: 'post_total'}]),避免 JavaScript 解释器瓶颈并充分利用原生 C++ 引擎优化。