• java mongoTemplate的group统计


    @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);
  • 相关阅读:
    STL
    Makefile
    配置pyqt5环境 for python3.4 on Linux Mint 17.1
    SELinux Policy Macros
    python爬虫
    python常用模块
    python中if __name__ == '__main__':
    Centos 7 .Net core后台守护进程Supervisor配置
    阅读Google Protocol Buffers 指南,整理pb语法
    Google Protocol Buffers 入门
  • 原文地址:https://www.cnblogs.com/yangzhenlong/p/7054207.html
Copyright © 2020-2023  润新知