【问题标题】:Mongo aggregation: Include a value's description stored in another collectionMongo 聚合:包括存储在另一个集合中的值的描述
【发布时间】:2018-06-27 14:37:56
【问题描述】:

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

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

有什么想法吗?

【问题讨论】:

    标签: mongodb projection


    【解决方案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"
            }
        }
    ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 2022-01-05
      • 1970-01-01
      • 2013-06-17
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      相关资源
      最近更新 更多