[英]MongoDB aggregation with spring
我正在尝试根据评论创建游戏排名。 我正在尝试获得明星的平均值并按游戏对其进行分组。 这是我的收藏的样子:
{
"_id": "31f6f1a8-4bfb-4753-b2d4-0acc296c3d91",
"title": "Cool game.",
"description": "The best game ever.",
"stars": 4,
"game": "xxx",
"_class": "com.example.demo.model.Review"
}
这是我在 Spring 中所做的:
@GetMapping(value = "/ranking")
public List<Review> getRanking() {
Aggregation aggregation = newAggregation(group("game").avg("stars").as("average"),
project("average").and("game").previousOperation());
AggregationResults<Review> results = mongoTemplate.aggregate(aggregation, "reviews", Review.class);
List<Review> finalResult = results.getMappedResults();
return finalResult;
这就是我在 Postman 中得到的:
"id": null,
"title": null,
"description": null,
"stars": null,
"game": "xxx"
我应该如何更改我的代码以仅获得每场比赛的平均星级?
这是您要找的东西吗?
db.collection.aggregate([
{
"$group": {
"_id": "$game",
"stars": {
"$avg": "$stars"
}
}
}
])
编辑:
您正在将星星的平均值投影为查询中的average
字段。 但我认为Review.java
没有average
字段。 因此它显示为空。
您可以做的是将星星的平均值投影为stars
如下所示:-
Aggregation aggregation = newAggregation(group("game").avg("stars").as("stars"),
project("stars").and("game").previousOperation());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.