繁体   English   中英

使用聚合管道在 MongoDB 中将功能从一个集合添加到另一个集合

[英]Add feature from one collection to another in MongoDB using the Aggregation Pipeline

我有两个与另一个相关的 collections usersgroups 一个用户只能在一个组中,而一个组可以包含多个用户。

Document A in users

{
  _id: 1234,
  name: "John Doe"
}

Document B in users

{
  _id: 2345,
  name: "Jane Roe"
}

Document G in groups

{
  _id: 3456,
  name: "A Group",
  members: [ObjectId("1234"), ObjectId("2345")]
}

现在我想在集合users上使用聚合管道将字段_group添加到每个用户以进行进一步处理。 添加的字段应包含用户所属组的 ID。

Result for Document A

{
  _id: 1234,
  name: "John Doe",
  _group: ObjectId("3456")
}

Result for Document B

{
  _id: 2345,
  name: "Jane Roe",
  _group: ObjectId("3456")
}

我真的不知道从哪里开始以及如何按照我描述的方式组合两个 collections。

这应该可以解决问题( https://mongoplayground.net/p/Iu53HQbi7Me ):

测试数据:

// users collection
[
    {
      _id: ObjectId("5a934e000102030405000001"),
      name: "John Doe"
    },
    {
      _id: ObjectId("5a934e000102030405000002"),
      name: "Jane Roe"
    }
]

// groups collection
[
    {
      _id: 100,
      name: "A Group",
      members: [
        ObjectId("5a934e000102030405000001"),
        ObjectId("5a934e000102030405000002")
      ]
    }
]

询问:

db.users.aggregate([
// join the two collections
  {
    $lookup: {
      "from": "groups",
      "localField": "_id",
      "foreignField": "members",
      "as": "membersInfo"
    }
  },
// unwind the membersInfo array
  {
    $unwind: "$membersInfo"
  },
  {
    $project: {
      "_id": {
        $cond: {
          "if": {
            $in: [
              "$_id",
              "$membersInfo.members" // replace _id field based on the members
            ]
          },
          "then": "$_id",
          "else": "No group"
        }
      },
      "name": 1, // mantain this field
      "_group": "$membersInfo._id" // create _group field using the _id of groups collection
    }
  }
])

结果:

[
  {
    "_group": 100,
    "_id": ObjectId("5a934e000102030405000001"),
    "name": "John Doe"
  },
  {
    "_group": 100,
    "_id": ObjectId("5a934e000102030405000002"),
    "name": "Jane Roe"
  }
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM