我有两个集合users
和groups
这些都与另一个。一个用户只能在一个组中,而一个组可以包含多个用户。
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"
}
]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句