spring data mongodb之Aggregation操做

TypedAggregation<Role> agg = Aggregation.newAggregation(Role.class,
                Aggregation.group("name").   //以name字段分组
                        sum("age").as("agesum"). //统计age的和并用agesum表示
                        first("age").as("agefirst"). //查出最小的年龄并用agefirst表示
                        addToSet("age").as("agess")  //把出现的全部年龄都加到set集合并用agess表示
                );
      
//UpdateScoreDto为自定义对象,把上面查出来的结果封装起来。
AggregationResults<UpdateScoreDto> results=mongoTemplate.aggregate(agg,UpdateScoreDto.class); 
List<UpdateScoreDto> list= results.getMappedResults();
查询结果以下所示
Document{{_id=zhang1, agesum=11, agefirst=5, agess=[6, 5]}}
Document{{_id=zhang2, agesum=6, agefirst=6, agess=[6]}}

参考:http://www.javashuo.com/article/p-dwkrfzvr-go.htmlapp

相关文章
相关标签/搜索