Reputation: 79
This is the query I used to get the average of rating, but the result was null:
db.products.aggregate([{$unwind: "$reviews"}, {$group: {_id: "$reviews", ratingAvg: {$avg: "$rating"}}}])
This is my product schema:
category: String,
name: String,
price: Number,
image: String,
description: String,
stock: Number,
reviews: [
{
type: mongoose.Schema.Types.ObjectID, ref: 'Review'
}
})
This is my review schema:
text: String,
rating: Number,
// author: {
// id: {type: mongoose.Schema.Types.ObjectID, ref: 'User'},
// name: String
// }
author: String
})
Every time I run this query I get:
{ "_id" : ObjectId("5f79d1b4b4b3c1061f1fbe52"), "ratingAvg" : null }
{ "_id" : ObjectId("5f79d1a5b4b3c1061f1fbe51"), "ratingAvg" : null }
{ "_id" : ObjectId("5f79d196b4b3c1061f1fbe4f"), "ratingAvg" : null }
It is showing ratingAvg as"null" whereas I have ratings for that product in my database.
Upvotes: 0
Views: 1980
Reputation: 8894
$lookup
helps to join two collections.
[
{
"$lookup": {
"from": "Review",
"localField": "reviews",
"foreignField": "_id",
"as": "reviews"
}
},
{
$unwind: "$reviews"
},
{
$group: {
_id: null,
ratingAvg: {
$avg: "$reviews.rating"
}
}
}
]
Then you can easily find the average using $avg
along with $group
after destructure the array using $uniwnd
Working Mongo playground
Upvotes: 2