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

时间:2018-03-01 22:01:39

标签: mongodb-query aggregation-framework

我有两个差异收藏品:

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",
}

1 个答案:

答案 0 :(得分: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'
    }
}
]);