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

Mongo aggregation: Include a value's description stored in another collection

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

{
    _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"
}

有什么想法吗?

您需要 $lookup to include values from other collection. As a result you'll get an array of all matching documents from specified collection so you can use $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"
        }
    }
])