標籤:
group by 查詢 不要用java驅動帶的group by ,要用2.2版本後的aggregate彙總架構來搞,經過實驗速度快一倍
參考
官網:http://docs.mongodb.org/manual/reference/sql-aggregation-comparison/
執行個體:http://www.yeetrack.com/?p=649
觀看例子前,請先看上面對的2個參考文檔,特別是官網的
例子
[java] view plaincopy
- // 首先利$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);
mongodb的進階操作(彙總架構)