繁体   English   中英

加入MongoDB MapReduce

[英]Joining in MongoDB MapReduce

我有2个收藏。

A: 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: ""}
    ]

你去了:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM