Populating in Mongodb Aggregating



我刚刚问了一个相关的问题:Mongoose/Mongodb Aggregate -组和平均多个字段

我试图使用Model.aggregate()按日期查找所有帖子的平均评级,然后按一些作者的子文档(如国家。名称或性别)查找。但在这方面遇到了麻烦。我知道在第一阶段,我只需要使用$match作为日期我认为我需要使用$lookup来"populate"作者字段,但不确定如何实现。

这适用于按日期查找所有帖子的平均评分:

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
}
}) 

可以在从MongoDB获取数据后填充聚合。你的"查询"将看起来像这样:

modelName.aggregate([{
$unwind: ''//if Needed
}, {
$group: {
_id: {"country":"$author.country.name"},
avgRating: {
$avg: '$rating'
}
}])
.exec(function(err, transactions) {
// ERRORHANDLING
// CallsBacks                
modelName.populate(columnName, {path: '_id'}, function(err, populatedModel) {
// Your populated columnName  inside TaleName
});
});

最新更新