I have a product model that looks thus:
{
"name":"Natural Product",
"ratings":[
{
"user":"5fdce4bd75dbe4864fcd5001",
"rating":5
},
{
"user":"5fdce4bd75dbe4864fcd5002",
"rating":4
}
]
}
I tried to get the average rating of the product model using the query below
db.products.aggregate([
{$match: {
_id: {$exists: true}
}},
{$group: {_id: "$_id", rating: { $avg: "$ratings.rating"}}}
])
But then the response I get looks thus:
{ "_id" : ObjectId("60baf573246539ec265efd41"), "rating" : null }
While trying to figure what the problem is, I inserted a new dummy data just with a slight difference in the structure that looks thus:
{
"name":"Natural Product",
"ratings":{
"user": "5fdce4bd75dbe4864fcd5001",
"rating": 5
}
}
It gave me this reasonable response:
{ "_id" : ObjectId("60bafb72246539ec265efd42"), "rating" : 5 }
How am I supposed to query the database to get the average of the ratings which is in array format, please?
{ $unwind: "$ratings" }, it will deconsturct the ratings array.