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

相關文章
相關標籤/搜索