【问题标题】:How to use aggregate functions with where conditions or find in mongoosejs如何在 where 条件下使用聚合函数或在 mongoosejs 中查找
【发布时间】:2020-12-21 07:00:10
【问题描述】:

我有如下评论模式:-

const reviewSchema = new mongoose.Schema({
    product:{
        type:Schema.Types.ObjectId,
        ref:'products',
        required:false,
        default:null
    },
    user:{
        type:Schema.Types.ObjectId,
        ref:'users',
        required:false,
        default:null
    },
    // status:{
    //     type:String,
    //     required:true,
    //     enum:['pending','approved','rejected'],
    //     default:"pending"
    // },
    rating:{
        type:Number,
        required:true
    },
    review:{
        type:String,
        required:false
    }
},{timestamps:true});

我想获得特定产品的平均评分到目前为止,我只能获得整个架构的平均评分

Review.aggregate([
            {
               "$group": {
                  "_id": null,
                  
                  "rating": {
                     "$avg": "$rating"
                  }
               }
            }
         ]
        ); 

我是 mongodb 环境的新手,来自 sql 背景。我尝试搜索,但找不到与此相关的任何内容。

P.s:- 我也尝试在 find method 之后绑定聚合。它不起作用。

提前致谢!

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    总的来说,您使用$match 管道作为条件。

    先用$match求产品,再用group求平均值。

    {
        { $match: { product: mongoose.Types.ObjectId('mongoIdForProductDoc') } },
        {
           $group: { ... your avg calculation }
        },
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多