一个查询,用于执行同一文档中两个数组之间的外部联接

时间:2015-12-24 04:15:36

标签: mongodb

给出以下集合结构:

db.two_lists.insert(
{
    "addresses":[
        {
            "studentId":1111,
            "addr":"1234 N Oak St.",
            "city":"Chicago",
            "state":"IL",
            "zipcode":60601
        },
                {
            "studentId":3333,
            "addr":"1234 N Oak St.",
            "city":"Chicago",
            "state":"IL",
            "zipcode":60601
        }
    ],
    "students":[
        {
            "id":1111,
            "name":'Frank Smith'
        },
        {
            "id":2222,
            "name":'Joe Smith'
        }
    ]
}
);

我正在尝试返回学生名单及其相应的地址。问题是这两个存储在单独的数组中。我需要通过studentId匹配它们。我找到了一种方法:

db.two_lists.aggregate([
    {$match:{}}
    ,{$unwind:"$students"}
    ,{$unwind:"$addresses"}
    ,{$project:{ addresses:1, students:1,
        sameId : {$cond: { if: { $eq: [ "$addresses.studentId", '$students.id' ] }, then: true, else: false }}}
    }
    ,{$match:{sameId:true}}
]);

不幸的是,我的查询删除了没有地址的学生(studentId:2222)。如何最好地处理这样的问题。不能改变收藏结构。

预期输出

{
    "result" : [ 
        {
            "_id" : ObjectId("567b6f3aba874c0b52280d49"),
            "addresses" : {
                "studentId" : 1111,
                "addr" : "1234 N Oak St.",
                "city" : "Chicago",
                "state" : "IL",
                "zipcode" : 60601
            },
            "students" : {
                "id" : 1111,
                "name" : "Frank Smith"
            }
        },
        {
            "students" : {
                "id" : 2222,
                "name" : "Joe Smith"
            }
        }
    ],
    "ok" : 1
}

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:

db.two_lists.aggregate([
    {$match:{}}
    ,{$unwind:"$students"}
    ,{$unwind:"$addresses"}
    ,{$project:{ students:1,
        addresses : {$cond: { if: { $eq: [ "$addresses.studentId", "$students.id" ] }, then: "$addresses", else: null }}}
    }
    ,{$group:{_id:{students:"$students"}, addresses:{$addToSet:"$addresses"}}}
]);

给了我很多我想要的结果:

{
    "result" : [ 
        {
            "_id" : {
                "students" : {
                    "id" : 2222,
                    "name" : "Joe Smith"
                }
            },
            "addresses" : [ 
                null
            ]
        }, 
        {
            "_id" : {
                "students" : {
                    "id" : 1111,
                    "name" : "Frank Smith"
                }
            },
            "addresses" : [ 
                null, 
                {
                    "studentId" : 1111,
                    "addr" : "1234 N Oak St.",
                    "city" : "Chicago",
                    "state" : "IL",
                    "zipcode" : 60601
                }
            ]
        }
    ],
    "ok" : 1
}