这是一个使用 spring-data-mongodb 进行聚合的示例。
假设 PostTotalSalary.class 的结果模型对象:
public class PostTotalSalary {
private String post; // "teacher" or "principal"
private Integer totalSalary;
}
我们将创建一个 GroupOperation 来收集所有具有相同值且键为“post”的文档
GroupOperation groupByPostAndSumSalary = group("post")
.sum("salary")
.as("totalSalary");
我们现在可以使用 spring-data-mongodb 创建一个聚合,然后将结果映射到您的结果模型对象(假设集合名称为“posts”):
Aggregation aggregation = Aggregation.newAggregation(groupByPostAndSumSalary);
AggregationResults<PostTotalSalary> groupResults = mongoTemplate.aggregate(aggregation, "posts", PostTotalSalary.class);
如果您想要一个列表,AggregationResults 有 getMappedResults 方法来执行此操作:
List<PostTotalSalary> mappedResults = groupResults.getMappedResults();
最终的结果是
[
{
"post" : "teacher",
"totalSalary" : "18000" // the total of all salaries for every "teacher" document
},
{
"post" : "principal",
"totalSalary" : "7000" // the total of all salaries for every "principal" document
}
]