MongoDB中使用MapReduce进行分组统计

2015-01-21 12:31:26 · 作者: · 浏览: 2

MongoDB中使用MapReduce进行分组统计


最近在统计某一个时间段的url去重数,由于数据量巨大导致报错,提示:


distinct failed: {


"errmsg" : "exception: distinct too big, 16mb cap",


"code" : 17217,


"ok" : 0


} at src/mongo/shell/collection.js:1108



经过查阅资料,最终通过mapreduce来解决如下:


//定义map函数


map=function(){


? ? emit(this.url,{"count":1});


}


//定义reduce函数


reduce=function(key,values){


? ? var total=0;


? ? for(var i=0; i < values.length; i++){


? ? ? ? total+=values[i].count;


? ? }


? ? return {count:total}


}


//执行mapreduce函数,其中out的值是存储执行结果的集合


db.runCommand({"mapreduce":"visit","map":map,"reduce":reduce,"query":{"vtime":{"$gte":1412611200,"$lte":1413907119}},"out":"test.tmp"});