node.js - 如何在猫鼬的集合中找到文档项的平均值?
问题描述
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
我怎样才能做到这一点?我无法弄清楚我们如何在猫鼬中找到平均值。任何帮助,将不胜感激。
解决方案
如果您想要合并所有记录的平均值,请尝试aggregate(),
$group
通过 null 并使用$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);
推荐阅读
- ios - 在 Objective-C 和 Swift 中编写不返回任何参数且不接受参数的闭包的所有有效方法是什么?
- javascript - 如何在 Vanilla JS 中编写:$(function() {...}?
- javascript - Javascript - 循环延迟 | 为什么这不起作用?
- javascript - 如何使用 socket.io 进行简单的消息传递并响应 useEffect()
- android - 撰写导航中没有方法导航(字符串)
- android - WorkManager 在继续下一个工作请求之前等待上传完成
- c++ - 深度图像的空间和时间平均
- java - 如何使用 String.format() 在 Java 中格式化双精度
- inheritance - XSLT 属性集依赖性报告/查询
- c# - WebView 和错误管理,有什么问题?