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