Recently, I inquired about a similar issue here: Mongoose/Mongodb Aggregate - group and average multiple fields
I am attempting to utilize Model.aggregate() to determine the average rating of all posts based on date and then further categorized by specific author attributes such as country name or gender. However, I am encountering difficulties in achieving this. I understand that for the initial stage, I need to use $match for filtering by date, and I believe I should employ $lookup to "populate" the author field, though the implementation is not clear to me.
The following code effectively computes the average rating for all posts based on date:
Post.aggregate([
{ $group: { _id: "$date", avgRating: { $avg: '$rating' }}}
]).
then(function (res) {
console.log(res);
})
Although this is essentially what I aim to do, it does not yield the desired results:
Post.aggregate([
{$match: {"date": today}},
{$group: {_id: {"country": "$author.country.name"}, avgRating: {$avg: "$rating"}}}
]).then(function(res) {
console.log(res)
})
User model details:
const userSchema = new Schema({
email: {
type: String,
required: true,
unique: true
},
birthday: {
type: Date,
required: true,
},
gender:{
type: String,
required: true
},
country:{
name: {
type: String,
required: true
},
flag: {
type: String,
// default: "/images/flags/US.png"
}
},
avatar: AvatarSchema,
displayName: String,
bio: String,
coverColor: {
type: String,
default: "#343a40"
},
posts: [
{
type: Schema.Types.ObjectId,
ref: "Post"
}
],
comments: [
{
type: Schema.Types.ObjectId,
ref: "Comment"
}
],
postedToday: {
type: Boolean,
default: false
},
todaysPost: {
type: String
}
})