加入 MongoDB 个 MapReduce

Joining in MongoDB MapReduce

我有 2 个 collections。

答: cid: 是一个 mongo object id,比如:ObjectId("xxxxxx") sid:可以是 NULL,也可以是 mongo object id,例如:ObjectId("xxxxxxx")

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

我想获取A中的所有文档(无论sid是否为null)。如果 sid 为 null,则 name 为空字符串:“”。如果不是,则名称是基于 sid 的形式 B。

当我寻找答案时,我知道 map 函数应该在两个 collections 上发出相同的键。但是,就我而言,我不能使用 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: ""}
    ]

好了:

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", "" ] },
    }
}])