返回数组元素MongoDB的总和

时间:2016-06-19 15:04:20

标签: json mongodb for-loop

我刚刚开始使用MongoDB并尝试从特定课程中获得学生的平均成绩。这里的大部分问题都涉及使用aggregate,$ sum或$ project,我将学生的课程名称和索引作为函数参数传递,我尝试迭代课程并总结值,但我想我有一个问题制定迭代以获得特定课程中特定学生的价值总和:

function (course, index) {

studcourses = db.students.find({course:course});
studnr = db.students.find({index:index});
results = [];
var sum = 0;
for (var i = 0; i < studcourses.length(); i++)
{
sum = sum + studcourses[i].grades;
}
mean = sum / studcourses.length();
results.push("Mean grade from course " + course + " for index: " + index + " " + mean);
return results;
}

以下是学生收藏的样子:

{
"_id": ObjectId("57644746473defc5128f8687"),
"index": 123345,
"name": "Andrew",
"surname": "Kaka",
"grades": {
 "DMI": [
   4,
   5,
   3,
   2 
],
 "IABD": [
   3,
   5,
   3,
   5 
],
 "NPAD": [
   2,
   4,
   5,
   2,
   4,
   5 
] 
} 
}

1 个答案:

答案 0 :(得分:0)

我假设您使用的是最新版本的MongoDB和NodeJS驱动程序,请尝试:

var find = function(course, idx){
  var grades = "$grades." + course;
  var result = db.collection.aggregate([
    {$match:{"index": ix}},
    {$project:{index:1, surname:1, total: {$sum: grades}, average: {$avg: grades}}}
  ]);

  return result;
};

您可以在代码中调用以上函数:

find("IABD", 123345);

假设您正在为学生索引IABD搜索课程123345,则上述代码将返回

{ 
    "_id" : ObjectId("57644746473defc5128f8687"), 
    "index" : NumberInt(123345), 
    "surname" : "Kaka", 
    "total" : NumberInt(16), 
    "average" : NumberInt(4)
}