mongodb - 在单个操作中使用 MongoDB 的多个聚合操作
问题描述
我有 2 个集合adminUser和departmentUseradminUserId
,它们由adminUser 集合和adminUserId
departmentUser集合中的字段链接。
我想合并这两个集合,其中包含两个集合的所有字段,无论它们之间的数据是常见的还是不常见的。我尝试使用聚合,但聚合仅返回具有公共字段的数据。
管理员用户:
{
"adminUserId" : "1"
"userName" : "Smith",
"position" : "Head"
},
{
"adminUserId" : "2"
"userName" : "Joe",
"position" : "Lead"
},
{
"adminUserId" : "3"
"userName" : "Mark",
"position" : "Lead"
}
部门用户:
{
"userId" : "1"
"userName" : "Leslie",
"position" : "Head",
"adminUserId" : ""
},
{
"userId" : "2"
"userName" : "Joe",
"position" : "Lead",
"adminUserId" : "2"
},
{
"userId" : "3"
"userName" : "Mark",
"position" : "Lead",
"adminUserId" : "3"
},
{
"userId" : "4"
"userName" : "Allen",
"position" : "Lead",
"adminUserId" : ""
}
输出:
{
"adminUserId" : "1"
"userName" : "Smith",
"position" : "Head"
},
{
"adminUserId" : "2"
"userName" : "Joe",
"position" : "Lead",
"departmentUserinfo":{
"userId" : "2"
"userName" : "Joe",
"position" : "Lead",
"adminUserId" : "2"
}
},
{
"adminUserId" : "3"
"userName" : "Mark",
"position" : "Lead",
"departmentUserinfo":{
"userId" : "2"
"userName" : "Mark",
"position" : "Lead",
"adminUserId" : "3"
}
},
{
"adminUserId" : ""
"userName" : "",
"position" : "",
"departmentUserinfo":{
"userId" : "1"
"userName" : "Leslie",
"position" : "Head",
"adminUserId" : ""
}
},
{
"adminUserId" : ""
"userName" : "",
"position" : "",
"departmentUserinfo":{
"userId" : "4"
"userName" : "Allen",
"position" : "Lead",
"adminUserId" : ""
}
}
任何人都可以帮忙吗?
解决方案
尝试这个 :
db.adminUser.aggregate([
{
$lookup:
{
from: "departmentUser",
localField: "adminUserId",
foreignField: "adminUserId",
as: "departmentUserinfo"
}
},
// As $lookup will result in an array i.e; departmentUserinfo will be an array, So getting first element out of it as we know it will always be [{}] --> If match found or [] --> If no match
{ $addFields: { departmentUserinfo: { $arrayElemAt: ['$departmentUserinfo', 0] } } }
])
结果 :
/* 1 */
{
"_id" : ObjectId("5e1757b919c2d113022f4584"),
"adminUserId" : "1",
"userName" : "Smith",
"position" : "Head"
}
/* 2 */
{
"_id" : ObjectId("5e1757b919c2d113022f4585"),
"adminUserId" : "2",
"userName" : "Joe",
"position" : "Lead",
"departmentUserinfo" : {
"_id" : ObjectId("5e1757f219c2d113022f4588"),
"userId" : "2",
"userName" : "Joe",
"position" : "Lead",
"adminUserId" : "2"
}
}
/* 3 */
{
"_id" : ObjectId("5e1757b919c2d113022f4586"),
"adminUserId" : "3",
"userName" : "Mark",
"position" : "Lead",
"departmentUserinfo" : {
"_id" : ObjectId("5e1757f219c2d113022f4589"),
"userId" : "3",
"userName" : "Mark",
"position" : "Lead",
"adminUserId" : "3"
}
}
推荐阅读
- java - 如何停止打印我的打印方法的一半
- ios - 如何获得最后一次看到的页面分析?
- angular - Angular程序菜单组件模板不起作用
- c# - 将字符串项从数组添加到对象列表
- visual-studio-code - 为什么颤振包会失败?从 github 克隆的相同目录但在一个 pc 包上失败
- windows-installer - 具有提升权限的 Installshield 自定义操作无法正常运行
- java - 如何从 Java 访问 Oracle 云存储
- c++ - 在 C++ 中获取元类类型
- excel - 基于复选框的电子邮件 - 如果函数
- python - 如何使用python在嵌套for循环中“输入”每个n个数字