表1:user 表
表2:dept表
需要查询user表中roleCodes 包含shr 的数据 然后联合dept表 需要部门名称
db.user.aggregate([
{
$match: {
roleCodes: "shr" // 匹配roleCodes包含"shr"的文档
}
},
{
$lookup: {
from: "dept", // 关联的集合名称
localField: "deptIds", // user表中用于关联的字段
foreignField: "id", // dept表中用于关联的字段
as: "deptInfo" // 关联后生成的字段名
}
},
{
$unwind: "$deptInfo" // 展开deptInfo数组
},
{
$project: {
_id: 0,
account: 1,
name: 1,
deptName: "$deptInfo.name" // 投影显示部门名称
}
}
])
让最后的数据 deptName 显示成集合 不要分开显示
db.user.aggregate([
{
$ma