'Mongoldb aggregation average of a number in an array?

I have a collection of documents that look like this

    {
 _id : 21353456,
product : "xy",
text : "asdf",
reviews : [
{
     username : "User1",
     userID: 12
     text : "hi"
     rate: 4,
     },
     {
     username : "User2",
     userID: 123
     text : "hi1"
     rate:2,
     }
    ]
}

I want to retrieve the average rating for user1 on all the product they have rated.

db.collection.aggregate([{$unwind: "$reviews"},{$match: {"$review.userID": "12"}},{$group: {  _id: "$reviews.userName", 
{avgRate: {$avg: "$reviews.rate"}}})] 
) 

I tried this but I keep getting unexpected token errors for "," where the last ")" is.



Solution 1:[1]

You did this:

db.collection.aggregate([
   { $unwind: "$reviews" },
   { $match: { "$review.userID": "12" } },
   { $group: { _id: "$reviews.userName", 
{ avgRate: { $avg: "$reviews.rate" } }})] 
) 

Must be this:

db.collection.aggregate([
   { $unwind: "$reviews" },
   { $match: { "$review.userID": "12" } },
   {
      $group: {
         _id: "$reviews.userName",
         avgRate: { $avg: "$reviews.rate" }
      }
   }
]) 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wernfried Domscheit