mongodb 在 mongoosejs 中取列的总和/平均值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12948511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Taking sum/average of columns in mongoosejs
提问by dany
I have a MongoDB collection "Marks" with fields student_id,Subject,Mark. I want to the average value of marks scored by a particular student. My project is in NodeJs and I am using MongooseJS for object modeling. How to query the this using MOngooseJS?
我有一个 MongoDB 集合“Marks”,其中包含字段 student_id、Subject、Mark。我想要特定学生得分的平均值。我的项目在 NodeJs 中,我使用 MongooseJS 进行对象建模。如何使用 MONgooseJS 查询 this?
EXAMPLE
例子
Student_id Subject Mark
111 AAA 9
111 BBB 5
111 CCC 7
222 AAA 10
222 CCC 6
222 BBB 8
I want average of marks scored by student(id) 111 i.e((9+5+7)/3)=7)
我想要学生(id)111的平均分数,即((9+5+7)/3)=7)
回答by JohnnyHK
If you're using MongoDB 2.2 you can use the aggregation framework for this:
如果您使用的是 MongoDB 2.2,您可以为此使用聚合框架:
var Mark = mongoose.model('mark', new Schema({
Student_id: Number,
Subject: String,
Mark: Number
}));
Mark.aggregate([
{ $group: {
_id: '$Student_id',
markAvg: { $avg: '$Mark'}
}}
], function (err, results) {
if (err) {
console.error(err);
} else {
console.log(results);
}
}
);
Output:
输出:
[ { _id: 222, markAvg: 8 }, { _id: 111, markAvg: 7 } ]
回答by Tigraine
This sounds like the poster child example of a Map/Reduce operation in MongoDB.
这听起来像是 MongoDB 中 Map/Reduce 操作的典型示例。
What you want to do is first run a map step where you emit all grades that belong to student id 111. Then you run the reduce step where you average these.
您想要做的是首先运行映射步骤,在该步骤中发出属于学生 ID 111 的所有成绩。然后运行减少步骤,对这些成绩求平均值。
The monogdb code should look similar to this:
monogdb 代码应该类似于:
var map = function() {
emit(this.Student_id, this.Mark);
}
var reduce = function(key, values) {
var result = { studentid: key, mark_sum: 0, count: 0, avg_mark: 0 };
values.forEach(function(v) {
r.mark_sum += v;
r.count += 1;
});
return r;
}
var finalize = function(key, value) {
if (value.count > 0) {
value.avg_mark = value.mark_sum / value.count;
}
return value;
}
And the execution of the mapReduce in Mongo syntax:
以及在 Mongo 语法中执行 mapReduce:
var command = db.runCommand( { mapreduce:"<your collection>",
map: map,
reduce: reduce,
query: { Student_id: 111 },
out: { reduce: "session_stat" },
finalize: finalize
});
The result of the map_reduce is written to session_stat. Where you can query it.
map_reduce 的结果被写入session_stat. 哪里可以查询。
To see how to use MapReduce in Mongoose please look at this Question: mongoose mapreduce()
要了解如何在 Mongoose 中使用 MapReduce,请查看这个问题:mongoose mapreduce()

