如何在猫鼬集合中找到文档项目的平均值?

时间:2020-10-23 06:29:08

标签: node.js mongodb api mongoose average

   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_roundsecond_round等。我怎样才能做到这一点?我不知道如何找到猫鼬的平均值。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

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

  • $group以空值表示,并使用$avg
  • 平均所有字段
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);

Playground

答案 1 :(得分:0)

您可以使用mongoDB aggregation来实现。并且在aggregation中,您可以使用$group来评估所有记录的每一轮平均值。

db.sales.aggregate(
 [
  { 
   $group:
     {
       _id: "$item",
       first_round_av: { $avg: "$first_round" },
       second_round_av: { $avg: "$second_round" },
       third_round_av: { $avg: "$third_round" },
     }
   }
  ]
 )
相关问题