如何在mongodb中加入2个以上的集合?

时间:2020-07-09 07:38:38

标签: mongodb mongoose nosql nosql-aggregation

我有3个收藏集:群组,用户和成员。 网上论坛集合包含网上论坛的详细信息, 用户集合包含特定于用户的详细信息和成员集合 包含用户与组的关联。

例如:

Groups:

id                                      |   name 
ObjectId("5ee5e346fae4a21e28a81d91")    |   Housemates 
ObjectId("5ee5e346fae4a21e28a81d92")    |   Co-workers


Users:

id                                      |   name
ObjectId("5ee493b0989d0f271cdc41c1")    |   Joulie
ObjectId("5ee493b0989d0f271cdc41c3")    |   Newelle
ObjectId("5ee493b0989d0f271cdc41c5")    |   John
ObjectId("5ee493b0989d0f271cdc41c7")    |   Larry

Members:
group_id                                | user_id  
ObjectId("5ee5e346fae4a21e28a81d91")    | ObjectId("5ee493b0989d0f271cdc41c1")
ObjectId("5ee5e346fae4a21e28a81d91")    | ObjectId("5ee493b0989d0f271cdc41c3")
ObjectId("5ee5e346fae4a21e28a81d92")    | ObjectId("5ee493b0989d0f271cdc41c5")
ObjectId("5ee5e346fae4a21e28a81d92")    | ObjectId("5ee493b0989d0f271cdc41c7")

我想加入这三个集合,并使用组名获取每个组的用户详细信息。

   Expected Output:
    [
        { "group_name":"Housemates", 
          "user_info": [
            {"name":"Joulie"},
            {"name":"Newelle"}
            ]
        },
        { "group_name":"Co-workers", 
          "user_info": [
            {"name":"John"},
            {"name":"Larry"}
            ]
        }
   ]

我编写了一个查询以获取如上所述的输出,但是它不起作用:

db.members.aggregate([
      {
        $lookup : {
          from: 'users',
          localField: "user_id",
          foreignField: "_id",
          as: "user_info"
        }
      },{
        $lookup: {
            from: 'groups',
            localField: "group_id",
            foreignField: "_id",
            as: "group_info"
        }
      }
    ]);

This这个问题看起来很相似,我也尝试过该解决方案,但是它似乎对我不起作用。我将不胜感激任何帮助或指导。 预先谢谢你!

1 个答案:

答案 0 :(得分:1)

您有一个正确的想法,我们只需要在查找后重建数据即可:

db.members.aggregate([
  {
    $lookup: {
      "from": "groups",
      "localField": "group_id",
      "foreignField": "_id",
      as: "groups"
    }
  },
  {
    $lookup: {
      "from": "users",
      "localField": "user_id",
      "foreignField": "_id",
      as: "users"
    }
  },
  {
    $unwind: "$groups"
  },
  {
    $unwind: "$users"
  },
  {
    $group: {
      _id: "$groups._id",
      group_name: {
        $first: "$groups.name"
      },
      user_info: {
        $addToSet: {
          name: "$users.name"
        }
      }
    }
  }
])

Mongo Playground