MongoDB-是否可以在MapReduce中编写几个不同的函数?

时间:2019-05-13 14:58:37

标签: mongodb mapreduce

作为我学习的一部分,我们最近开始学习MongoDB,所以我在该领域还很年轻。 在我们分配给的一项任务中,使用了MapReduce,但我做不到。

提供以下形式的学生集合:

{
_id: ObjectId("4ffmdjd8cfd99k03"),
tz: "11111",
FirstName: "Anton",
LastName: "Gill",
Department: "Computer Science"
Year: 1
Courses: [ { name: "Linear Algebra 1", grade: 70}, {name: "OS", grade: 88}]
}

任务是编写一个mapReduce函数,以便它返回每个系和每年的学生的姓名列表,所有这些学生的年级均大于90。正常输出示例:

[{Department: "Computer Science", Year: 1, students: ["Anton", "John"]},
{Department: "Physics", Year: 2, students: ["Dean", "David"]}]

我可以编写多个地图功能吗?也就是说,mapReduce结构将如下所示:

db.students.mapReduce(
    map1,
    map2,
    map3,
    ..
    reduce,
..

我尝试创建所需的结构失败。 这是我所能达到的最好水平,但我仍然不确定如何编写reduce函数。

var map = function(){
    var value = 0, n = this.Courses.length;
    for(var i = 0; i < n; i++){
        value += this.Courses[i].grade;
    }
    var avgGrade = value/n;
    if(avgGrade > 90){
        var key = {
        tz:this.tz,
        Department:this.Department,
        Year:this.Year,
        };
        value = {students:[this.FirstName]};
    }
    emit(key, value);
};

var reduce = function(keysObj, valuesObj){
    return 1000; //Ignore this function, I've no idea how to deal with it.
};

db.students.mapReduce(
    map,
    reduce,
    {
    out: "output",
    }
)

非常感谢您的协助:)

0 个答案:

没有答案