@Service public class MongoCountServiceImpl implements MongoCountService { @Autowired private MongoTemplate mongoTemplate; @Override public List<MongoCountDTO> count(String docName, String groupFeild, Query queryCondition) { //定义统计返回字段:默认添加以...分组的字段groupFeild、下面定义的count String reduce = "function(doc, aggr){" + " aggr.count += 1;" + " }"; DBObject result = mongoTemplate.getCollection(docName).group(new BasicDBObject(groupFeild, 1), queryCondition.getQueryObject(), new BasicDBObject("count", 0), reduce); List<Map> list = (List) JSON.toJSON(result); List<MongoCountDTO> countList = new ArrayList<>(); //组装全部 long all = 0; if(CollectionUtils.isNotEmpty(list)) { for (Map o : list) { long cou = ((Double) o.get("count")).longValue(); MongoCountDTO count = new MongoCountDTO((String) o.get(groupFeild), cou); countList.add(count); all = all + cou; } } MongoCountDTO allCount = new MongoCountDTO("全部", all); countList.add(0, allCount); return countList; } }
如果想要返回多个字段值:
String reduce = "function(doc, aggr){" + " aggr.count += 1;" + " aggr.province = doc.insure_province;" +//这里是想返回的字段:自定义字段=mongo里doc的字段 " }"; Query queryCondition = new Query(); DBObject result = mongoTemplate.getCollection("policy").group(new BasicDBObject("vehicle_type_no", 1), queryCondition.getQueryObject(), new BasicDBObject("count", 0), reduce); List<Map> list = (List) JSON.toJSON(result);
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/16955.html