0

我有一个集合,其中 student_id 是主键:

test1:{student_id:"xxxxx"},

我有另一个集合,其中 student_id 在集合数组中:

class:{"class":"I",students:["student_id":"xxxx"]}

我的问题是我想根据学生 ID 加入这两个表,

我正在使用 map reduce 和 out 作为“合并”,但它不起作用。

我的 MR 查询如下。

db.runCommand({ mapreduce: "test1", 
 map : function Map() {
    emit(this._id,this);
},
 reduce : function Reduce(key, values) {
    return values;
},

 out : { merge: "testmerge"  }
 });

 db.runCommand({ mapreduce: "class", 
 map : function Map() {
    emit(this._id,this);
},
 reduce : function Reduce(key, values) {
    return values;
},

 out : { merge: "testmerge"  }
 });

但它插入两行。

有人可以指导我吗,我对 MR 很陌生

在示例中,我想从“test1”集合中获取所有学生的详细信息,在“I”类学习。

4

1 回答 1

1

您的要求似乎是:

在示例中,我想从“test1”集合中获取所有学生的详细信息,在“I”类学习。

为了做到这一点,将学生所在的班级与学生一起存储:

{
    student_id: "xxxxx",
    classes: ["I"],
},

然后,您可以通过以下方式询问所有学生的信息:

db.students.find( { classes: "I" } );

无需任何缓慢而复杂的 map reduce 作业。一般来说,您应该避免使用 Map/Reduce,因为它不能使用索引并且不能同时运行。您还需要了解,在 MongoDB 中,操作仅在一个集合上完成。没有联接之类的东西,尝试用 Map/Reduce 模拟它是个坏主意。至少你可以用两个查询来做到这一点:

// find all students in class "I":
ids = []; 
db.classes.find( { class: "I" } ).forEach(function(e) { ids.push( e.student_id ) ; } );
// then with the result, find all of those students information:
db.students.find( { student_id: { $in: ids } } );

但我强烈建议您重新设计您的架构并将课程与每个学生一起存储。作为一般提示,与关系数据库相比,在 MongoDB 中,您会将文档之间的关系存储在另一端。

于 2013-08-07T10:57:34.950 回答