Mongo聚合:包含存储在另一个集合中的值的描述

时间:2018-06-27 14:37:57

标签: mongodb projection

我们有两个集合,第一个定义文件,简化了示例:

{
    _id: "00a00680-0e77-11e7-b757-edf2b0aec1f9",
    name: "someFileName.txt",
    numRows: 17,
    statusCode: 10
},
{
    _id: "0653b830-ac06-11e6-b5e3-7f4580599144",
    name: "someOtherFileName.txt",
    numRows: 134,
    statusCode: 12
},
...

和相关的statusCodes集合:

{
    statusCode: 10,
    statusCodeDesc, "This is the description for status code 10"
},
{
    statusCode: 12,
    statusCodeDesc, "This is the description for status code 12"
}
...

现在,我们使用聚合和投影以产生所需的输出,当前投影看起来像这样:

db.getCollection('files').aggregate([
    {$match: {_id: "00a00680-0e77-11e7-b757-edf2b0aec1f9"}},
    { "$project": {
        "id": "$_id",
        "name": "$name",
        "statusCode": "$statusCode"
    }}
])

产生所需的输出:

{
    _id: "00a00680-0e77-11e7-b757-edf2b0aec1f9",
    name: "someFileName.txt",
    numRows: 17,
    statusCode: 10
}

无论如何,我们想要包括来自statusCodes集合的相关状态描述,以便我们能够做到这一点:

{
    _id: "00a00680-0e77-11e7-b757-edf2b0aec1f9",
    name: "someFileName.txt",
    numRows: 17,
    statusCode: 10,
    statusCodeDesc: "This is the description for status code 10"
}

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您需要$lookup才能包含其他集合中的值。结果,您将获得指定集合中所有匹配文档的数组,因此您可以使用$unwind获取第一个(因为您可能对每个代码都有唯一的描述),然后使用$project获取最终的文件形状:`

db.files.aggregate([
    {
        $match: {
            _id: "00a00680-0e77-11e7-b757-edf2b0aec1f9"
        }
    },
    {
        $lookup: {
            from: "statusCodes",
            localField: "statusCode",
            foreignField: "statusCode",
            as: "statusCodeDetails"
        }
    },
    {
        $unwind: "$statusCodeDetails"
    },
    {
        $project: {
            _id: 1,
            name: 1,
            numRows: 1,
            statusCode: 1,
            statusCodeDesc: "$statusCodeDetails.statusCodeDesc"
        }
    }
])