1. 程式人生 > >mongodb的mapreduce分組統計

mongodb的mapreduce分組統計

//根據in_time(yyyy-MM-dd HH:mm:ss)欄位精確到天分組,統計數量
Criteria criteria = Criteria.where("parking_id").is(inParking.getParking_id())
        .and("in_time").gte(inParking.getStart_time())
        .lte(inParking.getEnd_time());
String map = "function(){emit(this.in_time.substring(0,13),{count:1});}";
String reducef = "function(key,values){var total = 0;for(var i=0;i<values.length;i++){total += values[i].count;} return total;}";
Query query = new Query(criteria);
MapReduceResults<BasicDBObject> mapReduceResults =
        mongoTemplate.mapReduce(query, "in_parking", map, reducef, BasicDBObject.class);
Iterator iterator = mapReduceResults.iterator();
while (iterator.hasNext()) {
    String jsonString = iterator.next().toString();
    JSONObject jsonObject = JSONObject.parseObject(jsonString);
//有個Bug,有時返回結果value是JSONObject物件 有時直接返回統計值
    if(jsonString.contains("count")){
        JSONObject valueObj = jsonObject.getJSONObject("value");
        Object count = valueObj.get("count");
        jsonObject.put("value",count);
    }
    jsonArray.add(jsonObject);
}

reduce的處理條數超過100時會用兩個reduce處理  第二次調reduce函式時 total會重新初始化 然後拋異常

將reduce函式改下如下方式:

String reducef = "function(key,values){var total = {count:0};for(var i=0;i<values.length;i++){total.count += values[i].count;} return total;}";