【发布时间】:2021-10-22 19:58:06
【问题描述】:
我刚刚在这里问了一个相关问题: Mongoose/Mongodb Aggregate - group and average multiple fields
我正在尝试使用 Model.aggregate() 按日期查找所有帖子的平均评分,然后按某些作者的子文档(如 country.name 或性别)查找平均评分。虽然遇到了麻烦。我知道在第一阶段我只需要使用 $match 作为日期,我想我需要使用 $lookup 来“填充”作者字段,但不知道如何实现。
这适用于按日期查找所有帖子的平均评分:
Post.aggregate([
{ $group: { _id: "$date", avgRating: { $avg: '$rating' }}}
]).
then(function (res) {
console.log(res);
})
这基本上是我想做的,但它不起作用:
Post.aggregate([
{$match: {"date": today}},
{$group: {_id: {"country": "$author.country.name"}, avgRating: {$avg: "$rating"}}}
]).then(function(res) {
console.log(res)
})
用户模型:
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
}
})
【问题讨论】:
标签: javascript mongodb mongoose aggregate populate