javascript - 使用聚合管道在 MongoDB 中将功能从一个集合添加到另一个集合
问题描述
我有两个集合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"
}
]
推荐阅读
- python - 在python中遇到一个脚本遍历数据的int错误,如何解决?
- c++ - g++ 编译包含的头文件:没有这样的文件或目录
- python - 如何在python中将数字添加到数据时间变量?
- python - Flask Ajax 调用,没有错误,但没有收到响应
- assembly - 汇编 SIMD 指令在 xmm 寄存器中移动 64 位寄存器?
- snowflake-cloud-data-platform - 雪花:如果在加载时大于列大小,如何截断数据?
- javascript - 指定组件道具的默认值
- node.js - 期望被测函数内部模拟的解析值
- jquery - jQuery 没有在我的 webpack encore 上定义
- arrays - 按日期排序对象数组的问题