如果查找ID在嵌入式文档mongodb中,如何有效地实现连接?

时间:2018-02-04 18:21:14

标签: mongodb mongodb-query aggregation-framework

考虑一个方案,user可以订阅多个channelschannel属于publisher

基本上有三个实体

1:用户

2:频道

3:发布者

以下是db中的示例保存数据:

{
  "_id" : ObjectId("5a7428b7408437d7155bbde9"),
  "name" : "some subscriber who is a user ",
    "channelSubscription" : {
      "5a740c88408437d7155bbdca" : {
      "_id" : "5a740c88408437d7155bbdca",
      "channel_name" : "1st channel",
      "channelBelongsTo" : "publisher._id" // replace id with publisher details
   },

    "5a7411dc408437d7155bbdcb" : {
       "_id" : "5a7411dc408437d7155bbdcb",
       "channel_name" : "2nd channel",
       "channelBelongsTo" : "someOtherPublisher._id" // replace id with publisher details
     }
   }
}

如何在此处建立联接以获取publisher详细信息,以便channelBelongsTo可以拥有发布商详细信息

1 个答案:

答案 0 :(得分:1)

您需要在此处使用聚合框架来实现所需的结果。聚合管道最初应创建一个新字段,该字段是hashmap的键/值对数组,可以使用 $addFields 管道步骤和$ objectToArray运算符实现。所以你的第一个管道步骤是:

{
    "_id" : ObjectId("5a7428b7408437d7155bbde9"),
    "name" : "some subscriber who is a user ",
    "channelSubscription" : {
        "5a740c88408437d7155bbdca" : {
            "_id" : "5a740c88408437d7155bbdca",
            "channel_name" : "1st channel",
            "channelBelongsTo" : "1"
        },
        "5a7411dc408437d7155bbdcb" : {
            "_id" : "5a7411dc408437d7155bbdcb",
            "channel_name" : "2nd channel",
            "channelBelongsTo" : "2"
        }
    },
    "subscriptions" : [ 
        {
            "k" : "5a740c88408437d7155bbdca",
            "v" : {
                "_id" : "5a740c88408437d7155bbdca",
                "channel_name" : "1st channel",
                "channelBelongsTo" : "1"
            }
        }, 
        {
            "k" : "5a7411dc408437d7155bbdcb",
            "v" : {
                "_id" : "5a7411dc408437d7155bbdcb",
                "channel_name" : "2nd channel",
                "channelBelongsTo" : "2"
            }
        }
    ]
}

产生

publisher

对于加入,您需要附加 $lookup 管道步骤,该步骤会获取db.user.aggregate([ { "$addFields": { "subscriptions": { "$objectToArray": "$channelSubscription" } } }, { "$lookup": { "from": "publisher", "localField": "subscriptions.v.channelBelongsTo", "foreignField": "_id", "as": "publishers" } } ]) 详细信息,详情请参阅:

{{1}}