Mongodb:从另一个集合中提取相应的值

问题描述 投票:0回答:1

我有两个差异集合:

CollectionA
{
"_id" : 1.0,
"1234" : "GROUP"
}

{
"_id" : 2.0,
"2345" : "SUBGROUP"
}


CollectionB
{
"_id" : 1.0,
"config" : "1234",
"description" : "DCS"
}


{
"_id" : 2.0,
"config" : "2345",
"description" : "BCS"
}

当我通过加入两个集合来编写查询查询时,我期待以下输出。我们能否通过使用$ lookup函数获取请求的输出?

{
"_id" : 1.0,
"config" : "GROUP",
"description" : "DCS",
}


{
"_id" : 2.0,
"config" : "SUBGROUP",
"description" : "BCS",
}
mongodb-query aggregation-framework
1个回答
0
投票

您可以像这样实现您的查询:

db.getCollection('a').aggregate([{
    $lookup: {
        from: 'b',
        localField: '_id',
        foreignField: '_id',
        as: 'data'
    }
},
{
    $unwind: '$data'
},
{
    $project: {
        config: '$1234', //In your schema you may have the same key instead of 1234 and 2345
        description: '$data.description'
    }
}
]);
© www.soinside.com 2019 - 2024. All rights reserved.