mongodb连接两个表与多个数组

时间:2019-06-11 06:48:00

标签: mongodb mongoose mongodb-query aggregation-framework

我有一个表成员,另一个是促销代码。

会员表:

/* 1 */
{
    "_id" : ObjectId("5b62e7050b13587e9febb8db"),
    "country_id" : "5a093507f1d45633844096ef",
    "type" : "Bronze",
    "price" : "30",
}
/* 2 */
{
    "_id" : ObjectId("5b6961175140b477032291b7"),
    "country_id" : "5a093507f1d45633844096ef",
    "type" : "Gold",
    "price" : "1000",
}....

促销代码表:

{
    "_id" : ObjectId("5cfe23fd075be65883f6d921"),
    "final_status" : 1,
    "membership" : [ 
        ObjectId("5b62e7050b13587e9febb8db"), 
        ObjectId("5b6961175140b477032291b7"), 
        ObjectId("5b6961285140b477032291b8"), 
        ObjectId("5b7567dd5b874856981b53d3"), 
        ObjectId("5bba1c3794c6761db256edbc")
    ],
    "month" : [ 
        "1", 
        "3"
    ]
}

此处,promomcode表具有成员资格ID。我想要带有会员资格的促销代码数据加入query.get带有会员资格详细信息的促销代码数据 请帮助我

1 个答案:

答案 0 :(得分:1)

在mongodb中将$ lookup用于左外部联接

db.promocode.aggregate([{
  $lookup: {
    from: 'membership',
    localField: 'membership',
    foreignField: '_id',
    as: 'memberships'
  }
}, {
  $project: {
    membership: 0
  }
}])