Mongodb聚合JSON数组字段,用于其他集合的匹配字段

时间:2018-01-09 11:07:35

标签: json mongodb aggregation-framework

我是mongodb的新手,我有两个这样的集合:

第一个集合名称为A

{
"_id": "1234",
"versions": [{

        "owner_id": ObjectId("100000"),
        "versions": 1,
        "type" : "info",
        "items" : ["item1","item3","item7"]


    },
    {

        "owner_id": ObjectId("100001"),
        "versions": 2,
        "type" : "bug",
        "OS": "Ubuntu",
        "Dependencies" : "Trim",
        "items" : ["item1","item7"]

    }
]}

第二个集合名称为B

{ "_id": ObjectId("100000"), "email": "abc@xyz.com" } { "_id": ObjectId("100001"), "email": "bbc@xyz.com"}

预期输出为:

{
"_id": "1234",
"versions":[{

        "owner_id": "abc@xyz.com",
        "versions": 1,
        "type" : "info",
        "items" : ["item1","item3","item7"]


    },
    {

        "owner_id": "bbc@xyz.com",
        "versions": 2,
        "type" : "bug",
        "OS": "Ubuntu",
        "Dependencies" : "Trim",
        "items" : ["item1","item7"]

    }
] }

我使用了mongo $ lookup,但我没有获得所需的输出 请帮忙。

谢谢!!!

1 个答案:

答案 0 :(得分:2)

您需要$unwind个版本,$lookupforeignField$project上的另一个集合,以获取匹配数组中的第一个元素$group回到原始文件格式

收集一个

> db.a.find()
{ "_id" : "1234", "versions" : [ { "owner_id" : "100000" }, { "owner_id" : "100001" }, { "owner_id" : "100001" } ] }

收集b

> db.b.find()
{ "_id" : "100000", "email" : "abc@xyz.com" }
{ "_id" : "100001", "email" : "bbc@xyz.com" }

聚合管道

> db.a.aggregate(
        [
            {$unwind:"$versions"},
            {$lookup : {from : "b", "localField":"versions.owner_id", "foreignField":"_id", as :"out"}}, 
            {$project : {"_id":1, "versions.owner_id":{$arrayElemAt:["$out.email",0]}}},
            {$group:{_id:"$_id", versions : {$push : "$versions"}}}
        ]   
    ).pretty()

输出

{
        "_id" : "1234",
        "versions" : [
                {
                        "owner_id" : "abc@xyz.com"
                },
                {
                        "owner_id" : "bbc@xyz.com"
                },
                {
                        "owner_id" : "bbc@xyz.com"
                }
        ]
}