mongodb聚合函数aggregation的用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33661044/article/details/80798739

1、首先需要自定义一个类,来表示你需要统计的属性以及统计之后的结果,这里的_id表示我要统计的属性,count表示这个属性的项目总数

class IntegralCount {
        int _id;
        int count;

        public int get_id() {
            return _id;
        }

        public void set_id(int _id) {
            this._id = _id;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }
    }

2、使用aggregation函数进行统计

2.1、创建查询条件,即过滤条件
Criteria criteria = Criteria.where("user").is(user);

2.2、新建聚合函数
 Aggregation agg = newAggregation(
                match(criteria),
                group("itemCode").count().as("count")
);

2.3、通过spring mongodb 模板scoreReopsitory查询
AggregationResults<IntegralCount>  results =                 scoreRepository.aggregationGroup(agg,IntegralCount.class);

2.4、得到结果
 List<IntegralCount> result = results.getMappedResults();
 result中保存了查询结果集合


猜你喜欢

转载自blog.csdn.net/qq_33661044/article/details/80798739