通过Map减少加入

时间:2013-08-07 10:24:33

标签: mongodb mongo-java

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

test1:{student_id:"xxxxx"},

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

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

我的问题是我想根据学生ID

加入这两个表

我使用map reduce和out作为“merge”,但它不起作用。

我的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”课程中学习。

1 个答案:

答案 0 :(得分:1)

您的要求似乎是:

  

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

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

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

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

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

无需缓慢而复杂的地图减少工作。通常,您应该避免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中,您将存储其他侧的文档与关系数据库之间的关系。

相关问题