1.脚本
db.runCommand({
mapreduce: "wx_local_user_group",
map : function Map() {
var bindsum=0,xzsum=0;
if(this.bindFlag==1)
bindsum = 1;
if(this.subscribeFlag==1)
xzsum = 1;
emit(
{"updateTime":this.updateTime.substr(0,this.updateTime.indexOf(' ')),"name":this.name},
{fssum:1,xzsum:xzsum,bindsum:bindsum}
);
},
reduce : function Reduce(key, values) {
var fssum=0,xzsum=0,bindsum=0;
for(var i in values){
fssum += values[i].fssum;
xzsum += values[i].xzsum;
bindsum += values[i].bindsum;
}
return {"fssum":fssum,"xzsum":xzsum,"bindsum":bindsum};
},
finalize : function Finalize(key, reduced) {
return {fssum:reduced.fssum,xzsum:reduced.xzsum,bindsum:reduced.bindsum};
},
query : {"updateTime":{$gte:"2015-01-01",$lte:"2015-06-08 23:59:59"}},
out : { merge: "wx_local_group_count_day" }
});
——-java实现
public boolean executeGroup_count_dayName(DBCollection user_group,String beginTime,String endTime){
// map 函数的js code
String map = "function Map() {" +
"var bindsum=0,xzsum=0;"+
"if(this.bindFlag==1) bindsum = 1;" +
"if(this.subscribeFlag==1) xzsum = 1; " +
"emit({'updateTime':this.updateTime.substr(0,this.updateTime.indexOf(' ')),'name':this.name}," +
"{fssum:1,xzsum:xzsum,bindsum:bindsum});}";
//reduce 函数的js code
String reduce = "function Reduce(key, values) {" +
"var fssum=0,xzsum=0,bindsum=0;" +
"for(var i in values){" +
"fssum += values[i].fssum;" +
"xzsum += values[i].xzsum;" +
"bindsum += values[i].bindsum;" +
"}" +
"return {'fssum':fssum,'xzsum':xzsum,'bindsum':bindsum}" +
"}";
String outputCollection = "wx_local_group_count_day";//输出到此集合
MapReduceCommand.OutputType type = MapReduceCommand.OutputType.MERGE;// 融合
DBObject query = new BasicDBObject();
DBObject timec = new BasicDBObject();
timec.put("$gte", beginTime);
timec.put("$lte", endTime+" 23:59:59");
query.put("updateTime", timec);
MapReduceCommand cmd = new MapReduceCommand(user_group, map, reduce, outputCollection, type, query);
String finalize = "function Finalize(key, reduced) {return {fssum:reduced.fssum,xzsum:reduced.xzsum,bindsum:reduced.bindsum};}";
cmd.setFinalize(finalize);
MapReduceOutput out = user_group.mapReduce(cmd);//执行maReduce
CommandResult result = out.getCommandResult();
boolean flag = result.ok();//执行完毕返回true
return flag;
}