Mongo分组取每组最大的一条记录

时间:2021-11-18 19:17:12

使用Spring-data-mongo统计每个班级最高成绩 classIds为List集合


Criteria criteria = Criteria.where("classId").in(classIds);


GroupOperation groupOperation = Aggregation.group("classId").max("score").as("score");


Aggregation agg = Aggregation.newAggregation(ClassScore.class,Aggregation.match(criteria),groupOperation);


AggregationResults<Map> results = mongoTemplate.aggregate(agg,ClassScore.class,Map.class);


 Map<String, Double> classMaxScoreMap = new HashMap<>();


 if(results.getMappedResults() != null && results.getMappedResults().size() != 0){


          for(Map map:results.getMappedResults()){


                       classMaxScoreMap.put(map.get("_id").toString(), Double.valueOf(map.get("score").toString()));


          }


 }


return classMaxScoreMap;


欢迎加入我们的交流群425783133