使用聚合管道将一个集合中的特征添加到 MongoDB 中的另一个集合

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

我有两个集合 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")
}

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

这应该可以解决问题 (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"
  }
]