group by 查询 不要用java驱动带的group by ,要用2.2版本后的aggregate聚合框架来搞,经过试验速度快一倍
参考
官网:http://docs.mongodb.org/manual/reference/sql-aggregation-comparison/
实例:http://www.yeetrack.com/?p=649
观看例子前,请先看上面对的2个参考文档,特别是官网的
例子
- // 首先利$match筛选出where条件
- BasicDBObject[] array = {
- new BasicDBObject("startTimeLong", new BasicDBObject("$gte",beginTime)),
- new BasicDBObject("startTimeLong", new BasicDBObject("$lt",endTime)) };
- BasicDBObject cond = new BasicDBObject();
- cond.put("$and", array);
- DBObject match = new BasicDBObject("$match", cond);
- // 利用$project拼装group需要的数据,包含optCode列、processTime列
- DBObject fields = new BasicDBObject("optCode", 1); // 接口
- fields.put("processTime", 1);// 耗时
- fields.put("provinceCode", 1);// 省份
- fields.put("channelSubCode", 1);// 渠道
- fields.put("platFormCode", 1);// 平台
- DBObject project = new BasicDBObject("$project", fields);
- // 利用$group进行分组
- DBObject _group = new BasicDBObject("provinceCode", "$provinceCode");
- _group.put("channelSubCode", "$channelSubCode");
- _group.put("platFormCode", "$platFormCode");
- _group.put("optCode", "$optCode");
- DBObject groupFields = new BasicDBObject("_id", _group);
- //总数
- groupFields.put("count", new BasicDBObject("$sum", 1));
- //求和
- groupFields.put("processTime_sum", new BasicDBObject("$sum","$processTime"));
- DBObject group = new BasicDBObject("$group", groupFields);
- AggregationOutput output = MongodbUtil.getLogInfoCollection().aggregate(match, project, group);