Mongo aggregate: return total average of array values

Viewed 1683

I have this data in mongodb

{ 
  "name": "FooBar",
  "__v": 0,
  "user_rating": [
  {
    "date": "2017-06-02T16:19:32.002Z",
    "user_rating": 5,
  },
  {
    "date": "2017-06-02T16:19:46.803Z",
    "user_rating": 3,
  },
  {
    "date": "2017-06-02T16:20:01.244Z",
    "user_rating": 5,
  },
  {
    "date": "2017-06-02T16:15:54.673Z",
    "user_rating": 3,
  },
  {
    "date": "2017-06-02T16:53:42.489Z",
    "user_rating": 5,
  }
 ]
}

I need to filter this to show the name of the store, the average rating, the total amount of ratings and the how many 5 ratings, how many 4 ratings etc.

This is what I am expecting:

[
  {
    "_id":"FooBar",
    "countRating":5,
    "averageRating":4.2,
    "ratings": [
       {"num":3,"count":2},
       {"num":5,"count":3}
     ]
  }
 ]

However, I can't seem to get the averageRating - instead I get the average for the two combined totals of each rating.

Here is my Mongo query:

 db.collection.aggregate([
      {
        $match: {"name": "FooBar"}
      },
      {
          $unwind: "$user_rating"
      },
      {
        $match: {"name": "FooBar"}
      },
        {
          $group: {
            _id: {
              "name": "$name",
              "rating": "$user_rating.user_rating"
            },
            averageRating: {$avg: "$user_rating.user_rating"},
            countRating: {$sum: 1}
        }
      },
      {
        $group: {
          _id: "$_id.name",
          countRating: {"$sum": "$totalRatings"},
          averageRating: {"$avg": "$averageRating"},
          "rating": {
            "$push": {
              "num": "$_id.rating",
              "count": "$totalRatings"
            }
          },
        }
      }]);

Can anyone help get the overall average here? Thanks!!

1 Answers
Related