业务需求及设计见前文:基于 MongoDB 动态字段设计的探索
根据专业计算各科平均分 (总分、最高分、最低分)
public Object avg(String major){
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.unwind("courseList"),
Aggregation.match(Criteria.where("major").is(major)),
Aggregation.group("courseList.name").avg("courseList.score").as("avg")
); // avg 可以替换成 sum, max, min 分别求各科总分、最高分、最低分
AggregationResults<BasicDBObject> aggregationResults = mongoTemplate.aggregate(aggregation, Student.class, BasicDBObject.class);
List<BasicDBObject> result = new ArrayList<>();
for(Iterator<BasicDBObject> iterator = aggregationResults.iterator(); iterator.hasNext();){
result.add(iterator.next());
}
return result;
}
计算个人总分数
public Object sum(String name){
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.unwind("courseList"),
Aggregation.match(Criteria.where("name").is(name)),
Aggregation.group("name").sum("courseList.score").as("sum")
);
AggregationResults<BasicDBObject> aggregationResults = mongoTemplate.aggregate(aggregation, Student.class, BasicDBObject.class);
List<BasicDBObject> result = new ArrayList<>();
for(Iterator<BasicDBObject> iterator = aggregationResults.iterator(); iterator.hasNext();){
result.add(iterator.next());
}
return result;
}
完整代码:GitHub
?
原文地址:https://www.cnblogs.com/victorbu/p/11293743.html
时间: 2024-12-29 16:57:17