加入MongoDB MapReduce

时间:2017-11-13 15:30:09

标签: mongodb mapreduce

我有2个收藏。

cid:是一个mongo对象id,如:ObjectId(" xxxxxx") sid:可以是NULL,也可以是mongo对象id,如:ObjectId(" xxxxxxx")

B: sid:是一个mongo对象id,如:ObjectId(" xxxxxxxx") name:是一个字符串,如:" hello"

我想在A中获取所有文档(无论sid是否为null)。如果sid为null,则name为空字符串:""。如果不是,那么名称是基于sid的表格B.

当我寻找答案时,我知道map函数应该在两个集合上发出相同的键。但是,在我的情况下,我不能使用sid作为密钥。如果我使用sid作为密钥,那么我将错过sid id为null(无名称)的文档。我想我必须用cid作为关键。

如果有人知道如何解决,请告诉我。 感谢。

更新

    A: 
    [
     {cid: ObjectId("59f7634b6260c927c0a144b0"), sid: ObjectId("59f7634b6260c927c0a144b1")},
     {cid: ObjectId("59f7634b6260c927c0a144b2"), sid: null}
    ]
    B: [{sid: ObjectId("59f7634b6260c927c0a144b1"), name: "hello"}]

我想要

    [
     {cid: ObjectId("59f7634b6260c927c0a144b0"), sid: ObjectId("59f7634b6260c927c0a144b1"), name: "hello"},
     {cid: ObjectId("59f7634b6260c927c0a144b2"), sid: null, name: ""}
    ]

1 个答案:

答案 0 :(得分:0)

你去了:

db.getCollection('A').aggregate([{
    $lookup:
    { // lookup data from B using the "sid" fields as the join key
        'from': 'B',
        'localField': 'sid',
        'foreignField': 'sid',
        'as': 'b'
    }
}, {
    $unwind: { // flatten the "b" array
        path: "$b",
        preserveNullAndEmptyArrays: true // make sure we do not drop the non-matched documents from A
    }
}, {
    $project: {
        "_id": 1,
        "cid": 1,
        "sid": 1,
        "hello": { $ifNull: [ "$b.name", "" ] },
    }
}])