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

我有两个系列,它们与另一个相关。一个用户只能位于一个组中,而一个组可以包含多个用户。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")]

}

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


Result for Document A


{

  _id: 1234,

  name: "John Doe",

  _group: ObjectId("3456")

}

Result for Document B


{

  _id: 2345,

  name: "Jane Roe",

  _group: ObjectId("3456")

}

我真的不知道从哪里开始,以及如何以我描述的方式将这两个系列结合起来。


LEATH
浏览 124回答 1
1回答

慕田峪4524236

这应该可以解决问题(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"  }]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript