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

时间:2018-12-03 22:56:04

标签: php mongodb mapreduce find

我正在使用MongoDB在PHP中创建一个基本的Search示例。我对MongoDb和php也很陌生。以下是集合students的示例文档。

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

我想创建一个地图归约函数,计算所有测验分数的平均分数。

我从以下代码开始:

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" }
               )

但是我不知道如何访问score中的type=quiz

1 个答案:

答案 0 :(得分:2)

    // 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")
));