【发布时间】:2013-08-10 16:12:29
【问题描述】:
我在 mongodb 中有 2 个集合
用户
{ "_id" : ObjectId("..."), "type" : "user", "user_id" : "U1" }
{ "_id" : ObjectId("..."), "type" : "user", "user_id" : "U2" }
{ "_id" : ObjectId("..."), "type" : "user", "user_id" : "U3" }
物品
{ "_id" : ObjectId("..."), "type" : "item", "item_id" : "I1" }
{ "_id" : ObjectId("..."), "type" : "item", "item_id" : "I2" }
{ "_id" : ObjectId("..."), "type" : "item", "item_id" : "I3" }
{ "_id" : ObjectId("..."), "type" : "item", "item_id" : "I4" }
我打算进行交叉连接以产生以下集合
User_Item
{ "_id" : ObjectId("..."), "type" : "user_item", "item_id" : "I1", "user_id" : "U1", "score" : 0 }
{ "_id" : ObjectId("..."), "type" : "user_item", "item_id" : "I1", "user_id" : "U2", "score" : 0 }
{ "_id" : ObjectId("..."), "type" : "user_item", "item_id" : "I1", "user_id" : "U3", "score" : 0 }
{ "_id" : ObjectId("..."), "type" : "user_item", "item_id" : "I2", "user_id" : "U1", "score" : 0 }
{ "_id" : ObjectId("..."), "type" : "user_item", "item_id" : "I2", "user_id" : "U2", "score" : 0 }
{ "_id" : ObjectId("..."), "type" : "user_item", "item_id" : "I2", "user_id" : "U3", "score" : 0 }
{ "_id" : ObjectId("..."), "type" : "user_item", "item_id" : "I3", "user_id" : "U1", "score" : 0 }
{ "_id" : ObjectId("..."), "type" : "user_item", "item_id" : "I3", "user_id" : "U2", "score" : 0 }
{ "_id" : ObjectId("..."), "type" : "user_item", "item_id" : "I3", "user_id" : "U3", "score" : 0 }
{ "_id" : ObjectId("..."), "type" : "user_item", "item_id" : "I4", "user_id" : "U1", "score" : 0 }
{ "_id" : ObjectId("..."), "type" : "user_item", "item_id" : "I4", "user_id" : "U2", "score" : 0 }
{ "_id" : ObjectId("..."), "type" : "user_item", "item_id" : "I4", "user_id" : "U3", "score" : 0 }
我可以使用以下代码检索它
db.item.find().
forEach( function (i) {
db.user.find().
forEach( function (u) {
var row = {};
row.type = "user_item";
row.item_id = i.item_id;
row.user_id = u.user_id;
row.score = 0;
db.user_item.insert(row);
});
});
但问题是这种方法在处理大数据时非常慢(U=10,000,I = 10,000)。有没有办法在 mongodb 中使用 map-reduce 产生相同的输出,并且 map-reduce 会明显更快(理论上是的)?
注意:没有外键
【问题讨论】:
-
您可以将两个系列合并为一个,但我不建议这样做,相反我会说您需要非常仔细地考虑您在这里所做的事情,这个过程不会通过任何事情达到最佳状态。
-
您似乎正在尝试在 NoSQL DB 中创建/实现规范化的关系模式,但这是行不通的。如果你想要一个规范化的数据模型,我建议你选择一个关系数据库,否则如果你想坚持使用 MongoDB,就开始嵌套你的集合,因为 MongoDB 不是为 JOIN 集合而设计的。