首页 > 解决方案 > 如何在猫鼬的集合中找到文档项的平均值?

问题描述

   const scoreSchema = new mongoose.Schema({
    rollno:{
        type:Number,
        unique: true
    },
    first_round:{
        type:Number,
        validate(value){
            if(value > 10){
                throw new Error('Maximum marks is 10')
            }
        }
    },
    second_round:{
        type:Number,
        validate(value){
            if(value > 10){
                throw new Error('Maximum marks is 10')
            }
        }
    },
    third_round:{
        type:Number,
        validate(value){
            if(value > 10){
                throw new Error('Maximum marks is 10')
            }
        }
    },
    total:{
        type:Number,
        }
});

我需要为所有合并的记录找到 等的first_round平均值。second_round我怎样才能做到这一点?我无法弄清楚我们如何在猫鼬中找到平均值。任何帮助,将不胜感激。

标签: node.jsmongodbapimongooseaverage

解决方案


如果您想要合并所有记录的平均值,请尝试aggregate()

let result = await ModelName.aggregate([
  // match condition to match for specific rollno
  // { $match: { rollno: { $in: [1,2] } } },
  {
    $group: {
      _id: null,
      total_average: { $avg: "$total" },
      first_round: { $avg: "$first_round" },
      second_round: { $avg: "$second_round" },
      third_round: { $avg: "$third_round" }
    }
  }
], { allowDiskUse: true });
console.log(result);

操场


推荐阅读