[英]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.