1. 程式人生 > >mongo與Java之aggregate

mongo與Java之aggregate

使用aggregate實現分組功能:
–指令碼

db.wx_local_group_count_day.aggregate(
{"$match":{"_id.name":{$in:["阪田", "南灣", "平湖", "龍崗", "橫崗", "龍城", "坪地", "布吉"]},
            "_id.updateTime":{$gte:"2015-06-01",$lte:"2015-06-10 23:59:59"}
          }
    },
{"$group":{
    "_id":"$_id.updateTime",
    "fssum":{"$sum":"$value
.fssum"
}, "xzsum":{"$sum":"$value.xzsum"}, "bdfssum":{"$sum":"$value.bindsum"} } }, {"$sort":{"_id":-1}} );

$match—是查詢條件
$group—分組內容 其中的Key “_id”是必須的.

Java實現 上述指令碼

/**
     *  拼接日期查詢格式
     * */
    public DBObject  searchTime(String startTime,String endTime){
        DBObject timeC = new
BasicDBObject(); if (StringHelper.isNotNull(startTime)) { startTime = startTime; timeC.put("$gte", startTime); } if (StringHelper.isNotNull(endTime)) { endTime = endTime + " " + "23:59:59"; timeC.put("$lte", endTime); } return
timeC; } DBObject timeC = searchTime("2015-06-01","2015-06-10"); List<String> zxs = Arrays.asList(new String[]{"阪田","南灣"...}); String gsmc = ""; //aggregate實現分組加排序 public List<Map> dayGroup(DBObject timeC,List zxs,String gsmc){ List list = new ArrayList(); BasicDBObject in = new BasicDBObject(); //查詢條件 in.append("_id.name", new BasicDBObject("$in", zxs)); in.append("_id.updateTime", timeC); BasicDBObject math = new BasicDBObject(); math.append("$match",in); BasicDBObject groupby = new BasicDBObject();//分組統計 groupby.append("_id", "$_id.updateTime"); groupby.append("fssum", new BasicDBObject("$sum", "$value.fssum")); groupby.append("xzsum", new BasicDBObject("$sum", "$value.xzsum")); groupby.append("bdfssum", new BasicDBObject("$sum", "$value.bindsum")); BasicDBObject group = new BasicDBObject(); group.append("$group", groupby); BasicDBObject sort = new BasicDBObject(); sort.append("$sort", new BasicDBObject("_id", -1)); //按updateTime倒序排 DBObject obj = (DBObject) groupCountDayDao.groupByAggregate(math, group, sort); JSONArray jsonarr = JSONArray.fromObject(obj);// 必須轉成JSONArray, 轉JSONObject會報錯. for(int i = 0;i<jsonarr.size();i++){ JSONObject json = (JSONObject) jsonarr.get(i); Map map = new HashMap(); map.put("updateTime", json.getString("_id")); map.put("fssum", json.getInt("fssum")); map.put("xzsum", json.getInt("xzsum")); map.put("bdfssum", json.getInt("bdfssum")); map.put("gsmc",gsmc); list.add(map); } return list; }