java mongodb多條件聚合查詢
阿新 • • 發佈:2018-12-24
業務邏輯,
查詢符合 :1、大於且小於時間 2、按atype2欄位篩選 3、按人數字段求和 4、按省欄位聚合
下面程式碼,可以直接拿來用。
public List<DBObject> deathnumberByProvince(String startDate, String endDate,String type2) { List<DBObject> optionList = new ArrayList<>(); //mongodb查詢 BasicDBObject gteMoneyStart = new BasicDBObject("originaltime",new BasicDBObject("$gte", startDate) ); BasicDBObject matchMoneyStart = new BasicDBObject("$match", gteMoneyStart); optionList.add(matchMoneyStart); BasicDBObject gteMoneyEnd = new BasicDBObject("originaltime",new BasicDBObject("$lte", endDate) ); BasicDBObject matchMoneyEnd = new BasicDBObject("$match", gteMoneyEnd); optionList.add(matchMoneyEnd); BasicDBObject query = new BasicDBObject("atype2", type2); BasicDBObject matchProvince = new BasicDBObject("$match", query); optionList.add(matchProvince); DBObject groupFields=new BasicDBObject(); groupFields = new BasicDBObject( "_id", "$province"); groupFields.put("deathnumber", new BasicDBObject( "$sum", "$deathnumber")); DBObject group = new BasicDBObject("$group", groupFields); optionList.add(group); DBCollection collection = MongoDBUtil.getDBCollection("acc"); List<DBObject> results = (List<DBObject>) collection.aggregate(optionList).results(); return results; }