【问题标题】:Populating in Mongodb Aggregating填充MongoDB聚合
【发布时间】: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


    【解决方案1】:

    您可以在从 MongoDB 获取数据后填充聚合。您的 `Query 看起来有点像这样:

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

    【讨论】:

    • 在这种情况下 columnName 是什么?我正在尝试填充“作者”字段,该字段本身具有 {country: name, flag} 字段
    猜你喜欢
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 2014-12-11
    • 2021-02-16
    • 2021-04-21
    • 2020-04-18
    • 1970-01-01
    • 2021-04-25
    相关资源
    最近更新 更多