我有一个用户集合,看起来像这样-
{ "post": "teacher",
"salary": 4500
},
{ "post": "teacher",
"salary": 9000
},
{ "post": "principal",
"salary": 7000
},
{ "post": "teacher",
"salary": 4500
}
我想计算所有老师的工资总额,校长的工资也是如此。所以我想要看起来像这样的东西
"teachers_salary": 18000
"principals_salary": 7000
我想使用聚合,但没有得到所需的输出。如果你们中的任何人能帮助我找到解决方案,那将非常有帮助。
最佳答案
这是使用 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
}
]
关于java - 我应该如何使用 Spring Data MongoDB 计算由另一个字段分组的字段总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66991237/