我有两个集合"Employee","Office“
我正在尝试找出有多少员工在每个包含办公室代码的区域。但在同一地区可能有不止一个办公室。
这就是我的Office文档的外观
[
{
_id: "5b7d0f77e231b6b530b0ee5a",
code: "OB123456",
city: "Canmore"
// some other fields
},
{
_id: "5b7d0f77e531b6b530b0ee5b",
code: "OB858758",
city: "Vancouver"
},
{
_id: "5b7d0f77e531b6b530b0ee5d",
code: "EE858758",
city: "Vancouver"
},
]这就是我的员工文档可能的样子
[
{
_id: "5b7d0f77e531b6b530b0edda",
name: 'Charlie',
office: {
code: 'OB123456'
// some other fields
}
},
{
_id: "5b7d0f73e531b6b530b0ee5b",
name: 'Bill',
office: {
code: 'EE858758'
}
},
{
_id: "5b7d0f77e531b6b530b0ee5n",
name: 'Echo',
office: {
code: 'OB123456'
}
},
];我正在研究mongoose聚合,并且只尝试过
await Employee.aggregate([
{
$lookup: {
from: 'offices',
localField: 'office.code',
foreignField: 'code',
as: 'officeCode'
},
$group: {
_id: 'officeCode.city',
count: { $sum: 1 }
}
}
]);这肯定不起作用,我试着阅读了一些聚合文档,但想不出如何做到这一点的好主意
提前感谢您的任何建议或建议。
我正在寻找的样例输出
{
"Vancouver": 1,
"Canmore": 2
}发布于 2020-11-20 05:50:42
你必须从办公室开始,而不是从员工开始,所以你可以为每个地区(城市)创建一个代码列表,然后查找以映射到你的员工。
db.office.aggregate([
{
$group: {
_id: "$city",
codes: {
$addToSet: "$code"
}
}
},
{
$lookup: {
from: "employee",
localField: "codes",
foreignField: "office.code",
as: "employees"
},
},
{
$group: {
_id: null,
data: {
$push: {
k: "$_id",
v: {
$size: "$employees"
}
}
}
}
},
{
$replaceRoot: {
newRoot: {
"$arrayToObject": "$data"
}
}
}
])最后两个阶段仅用于格式化预期输出中描述的结果。
https://stackoverflow.com/questions/64885382
复制相似问题