MongoDB 的 MapReduce 相当于 Mysql 中的"group by", 所以在 MongoDB 上使用 Map/Reduce 进行并行"统计"很容易。
使用 MapReduce 要实现两个函数 Map 函数和 Reduce 函数,Map 函数调用 emit(key, value), 遍历 collection中所有记录, key 与 value 传递给 Reduce 函数进行处理。 函数和 Reduce 将 Map 函数可以使用 JavaScript 来实现,可以通db.runCommand 或 mapReduce 命令来执行一个 MapReduce 的操作。
参数说明
mapreduce: 要操作的目标集合。
map: 映射函数 (生成键值对序列,作为 reduce 函数参数)。
reduce: 统计函数。
query: 目标记录过滤。
sort: 目标记录排序。
limit: 限制目标记录数量。
out: 统计结果存放集合 (不指定则使用临时集合,在客户端断开后自动删除)。
keeptemp: 是否保留临时集合。
finalize: 最终处理函数 (对 reduce 返回结果进行最终整理后存入结果集合)。
scope: 向 map、reduce、finalize 导入外部变量。
verbose: 显示详细的时间统计信息。
8.1 Map
Map 函数必须调用 emit(key, value) 返回键值对,使用 this 访问当前待处理的 Document。
m = function() { emit(this.classid, 1) }
value 可以使用 JSON Object 传递 (支持多个属性值)。例如:
emit(this.classid, {count:1})
8.2 Reduce
Reduce 函数接收的参数类似 Group 效果,将 Map 返回的键值序列组合成 { key, [value1, value2, value3, value...] } 传递给 reduce。
r = function(key, values) {
var x = 0;
values.forEach(function(v) { x += v });
return x;
}
8.3 Result
res = db.runCommand({
mapreduce:"students",
map:m,
reduce:r,
out:"students_res"
});
mapReduce() 将结果存储在 "students_res" 表中。
8.4 Finalize
利用 finalize() 我们可以对 reduce() 的结果做进一步处理。
f = function(key, value) { return {classid:key, count:value}; }
列名变与 “classid”和”count”了,这样的列表更容易理解。
8.5 Options
可以添加更多的控制细节 。添加query、sort等。