时间:2021-07-01 10:21:17 帮助过:13人阅读
业务需求及设计见前文:基于 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
参考:MongoTemplate 聚合操作
?基于 MongoDB 动态字段设计的探索 (二) 聚合操作
标签:array mui mob for post template ++ 聚合操作 sga