MongoDB 聚合(aggregate() 方法)
1 語法
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
2 答題表定義
學(xué)生ID
userId
股淡,題目IDquestionId
,課程名subject
各聘,回答內(nèi)容answerCtn
揣非,得分score
/* 回答內(nèi)容定義 */
var answerSchema = new Schema({
userId: {type: ObjectId, ref: 'User'},
questionId: {type: ObjectId, ref: 'Question'},
subject: String,
answerCtn: String,
score: Number,
meta: {
updateAt: {type:Date, default: Date.now()},
createAt: {type:Date, default: Date.now()}
}
});
3 學(xué)生成績表定義
學(xué)生ID
userId
,課程名subject
躲因,成績score
/* 學(xué)生成績定義 */
var gradeSchema = new Schema({
userId: {type: ObjectId, ref: 'User'},
subject: String,
score: Number,
meta: {
updateAt: {type:Date, default: Date.now()},
createAt: {type:Date, default: Date.now()}
}
});
4 統(tǒng)計方法
- 成績統(tǒng)計是指對某一個學(xué)生的某門課程每道題目得分的總和早敬。
-
aggregate()
方法先利用$match
查詢處課程為WEB
的答題列表,$group
將學(xué)生ID一樣的數(shù)據(jù)組合成一個集合大脉,$sum
計算同一集合里的score
總和 - 將
aggregate()
結(jié)果依次保存進學(xué)生成績表grade
搞监。
//統(tǒng)計成績
exports.statisticScore = function (data, cb) {
async.waterfall([
function (cb) {
Answer.aggregate([
{ $match: { subject: "WEB" }},
{ $group: { _id: "$userId", totalScore: { $sum: "$score" }}}
], function (err, docs) {
if (err) {
console.log(err);
} else {
cb(err, docs);
}
});
},
function (result, cb) {
for(var i = 0; i < result.length; i++) {
var grade = new Grade({
userId: result[i]._id,
subject: "WEB",
score: result[i].totalScore
});
grade.save(function (err, doc) {
if(err) {
console.log(err);
entries.code = 99;
}
});
}
cb(null, entries);
}
], function (err, result) {
cb(true, result);
});
console.log("done");
};