日期:2014-05-16  浏览次数:20514 次

mongo MapReduce例子

?

第八章?MapReduce

MongoDB的MapReduce相当于Mysql中的"group by",所以在MongoDB上使用 Map/Reduce 进行并行"统计"很容易。

?

使用MapReduce要实现两个函数 Map函数和Reduce函数,Map函数调用emit(key, value),遍历collection中所有的记录,将key与value传递给Reduce函数进行处理。Map函数和Reduce函数可以使用JavaScript来实现,可以通过db.runCommand或mapReduce命令来执行一个MapReduce的操作:

?

?

db.runCommand(

{ mapreduce : <collection>,

? ?map : <mapfunction>,

? ?reduce : <reducefunction>

? ?[, query : <query filter object>]

? ?[, sort : <sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces>]

? ?[, limit : <number of objects to return from collection>]

? ?[, out : <see output options below>]

? ?[, keeptemp: <true|false>]

? ?[, finalize : <finalizefunction>]

? ?[, scope : <object where fields go into javascript global scope >]

? ?[, verbose : true]

}

);

?

参数说明:

l??mapreduce: 要操作的目标集合。

l??map: 映射函数 (生成键值对序列,作为 reduce 函数参数)。

l??reduce: 统计函数。

l??query: 目标记录过滤。

l??sort: 目标记录排序。

l??limit: 限制目标记录数量。

l??out: 统计结果存放集合 (不指定则使用临时集合,在客户端断开后自动删除)。