如何在 MongoDb 中创建 MapReduce 查询来计算平均考试成绩?

How to create a MapReduce query in MongoDb to calculate average of exam scores?

我正在使用 MongoDB 在 PHP 中创建一个基本搜索示例。我也是 MongoDb 和 php 的新手。以下是集合 students.

的示例文档
 { "_id" : 1, 
   "name" : "xyz", 
   "scores" : [ 
                { "score" : 60.06045071030959, "type" : "exam" }, 
                { "score" : 52.79790691903873, "type" : "quiz" }, 
                { "score" : 71.76133439165544, "type" : "homework" } 
              ] 
 }

我想创建一个 map reduce 函数来计算所有测验分数的平均分数。

我从以下代码开始:

var mapFunction1 = function() {
                   emit(this._id, this.exam);
               };

var reduceFunction1 = function(keyId, examscore) {
                      return Array.sum(examscore);
                  };


db.students.mapReduce(
                 mapFunction1,
                 reduceFunction1,
                 { out: "map_reduce_example" }
               )

但是我不知道,如何访问 type=quizscore

    // construct map and reduce functions
$map = new MongoCode("function() {".
    "for (var idx = 0; idx < this.scores.length; idx++) {".
     "var key = this.scores[idx].type;".
     " var value = {".
     " count: 1,".
     " score: this.scores[idx].score ".
     "};".
     "emit(key, value);".
"}".
"};");
$reduce = new MongoCode("function(keyType, countObjVals) {".
    "reducedVal = { count: 0, score: 0 };".

   " for (var idx = 0; idx < countObjVals.length; idx++) {".
    "    reducedVal.count += countObjVals[idx].count;".
    "    reducedVal.score += countObjVals[idx].score;".
   " }".

   " return reducedVal;".
" };");
$finalizeFun = new MongoCode(
    "function (key, reducedVal) {".

      " reducedVal.avg = reducedVal.score/reducedVal.count;".

      " return reducedVal;".

    "};");
$students = $db->command(array(
    "mapreduce" => "students", 
    "map" => $map,`enter code here`
    "reduce" => $reduce,`enter code here`
    'finalize' => $finalizeFun,
    "out" => array("merge" => "eventCounts")
));