简体   繁体   中英

MongoDB aggregation with spring

I am trying to create a ranking of games based on reviews. I'm trying to get average of stars and group it by games. This is how my collection looks like:

{
  "_id": "31f6f1a8-4bfb-4753-b2d4-0acc296c3d91",
  "title": "Cool game.",
  "description": "The best game ever.",
  "stars": 4,
  "game": "xxx",
  "_class": "com.example.demo.model.Review"
}

This is what I did in 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;

And this is what I get in Postman:

    "id": null,
    "title": null,
    "description": null,
    "stars": null,
    "game": "xxx"

How should I change my code to get only average of stars for every game?

Is this something you are looking for?

db.collection.aggregate([
  {
    "$group": {
      "_id": "$game",
      "stars": {
        "$avg": "$stars"
      }
    }
  }
])

Mongo Playground

EDIT:

You are projecting the average of stars as average field in query. But i think there is no average field in Review.java . Hence it is showing null.

What you can do is project the average of stars as stars like so :-

Aggregation aggregation = newAggregation(group("game").avg("stars").as("stars"),
        project("stars").and("game").previousOperation());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM