https://www.cnblogs.com/zhangzxl/p/4079641.html
mongodb中的分组聚合用$group,而且处理的最大数据量为100M如果超出需要写入到磁盘,使用格式如下:
1 |
|
其中_id属性是必须要有的,目的是用来指定分组的字段或依据,field1为自定义字段,accumulator为累加器,下面以统计每天用户注册数为列
1 2 3 4 5 6 7 8 9 10 11 12 |
|
如果只想注册地区为四川的则在$goup前增加一个$match:
1 2 3 4 5 |
|
以上两个聚合操作的java实现方式:
DBObject filterCond = new BasicDBObject(); filterCond.put("location", "SiChuan"); DBObject match = new BasicDBObject("$match", filterCond);
BasicDBList dateList = new BasicDBList(); dateList.add("$time"); dateList.add(28800000);//解决timezone 8小时时差 DBObject time = new BasicDBObject("$add", dateList);
DBObject group = new BasicDBObject(); DBObject groupDate = new BasicDBObject(); groupDate.put("year", new BasicDBObject("$year", time)); groupDate.put("month", new BasicDBObject("$month", time)); groupDate.put("day", new BasicDBObject("$dayOfMonth", time)); group.put("$group", new BasicDBObject("_id", groupDate));
AggregationOutput output = coll.aggregate(match, group); Iterator iterator = output.results().iterator();
更多的聚合操作请参见这》》》http://docs.mongodb.org/manual/reference/operator/aggregation-pipeline/