//根据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;}";