IT虾米网

java mongoTemplate的group统计详解

developer 2019年09月24日 编程语言 1001 0
@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);

 

发布评论

分享到:

IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

java8 从对象集合中取出某个字段的集合详解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。