重點探討mongodb 對某個欄位 sum求和
new BasicDBObject("$group",new BasicDBObject("_id","$number").append("total", new BasicDBObject("$sum","$"+"length")));
new BasicDBObject("_id","$"+queryField)為固定格式
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);
/*** 對一個欄位求和* @param collectionName* @param where* @param groupFields* @return*/public Double sum(String collectionName,DBObject where,String sumField){DBCollection col=mongoDbFactory.getDb().getCollection(collectionName);DBObject match=new BasicDBObject("$match",where);DBObject group=new BasicDBObject("$group",new BasicDBObject("_id",null).append("total", new BasicDBObject("$sum","$"+sumField)));List<DBObject> list=(List<DBObject>)col.aggregate(match,group).results();if(list.size()>0){return Double.valueOf(list.get(0).get("total").toString());}return 0D;}
個人執行個體:查詢消費總和
public long getCostCount(String number, String type, int month) {DBCollection dbc = getCollection(Constant.MongoDBName, Constant.CostDetails);DBObject dbObject = new BasicDBObject();dbObject.put("number", number);dbObject.put("type", type);dbObject.put("month", month);//設定Where條件 DBObject match = new BasicDBObject("$match",dbObject); //設定分組欄位 DBObject group=new BasicDBObject("$group",new BasicDBObject("_id","$number").append("total", new BasicDBObject("$sum","$"+"length")));List<DBObject> list=(List<DBObject>)dbc.aggregate(match,group).results();if(list != null && list.size()>0){LOG.info(list.get(0).toString());return Long.valueOf(list.get(0).get("total").toString());}else{return 0l;}}