我尝试做的是按主要和次要角色对用户进行分组,并计算具有所述角色的用户数量。用户列表如下所示:
DownloadStatus
结果应该是这样的:
[
{
_id: 1,
roles: {
primary: 'Cook',
secondary: null
}
},
{
_id: 2,
roles: {
primary: 'Waiter',
secondary: 'Cashier'
}
},
{
_id: 3,
roles: {
primary: 'Cashier',
secondary: 'Bar Tender'
}
}
]
我不太确定这是否可行,至少在一次[
{
role: 'Cook',
count: 1
},
{
role: 'Waiter',
count: 1
},
{
role: 'Cashier',
count: 2
}
]
电话中是这样。
答案 0 :(得分:1)
您可以将两个字段值都放入数组$unwind
然后$group
:
db.collection('crap').aggregate([
{ "$project": {
"roles": {
"$filter": {
"input": ["$roles.primary","$roles.secondary"],
"cond": { "$ne": [ "$$this", null ] }
}
}
}},
{ "$unwind": "$roles" },
{ "$group": {
"_id": "$roles",
"count": { "$sum": 1 }
}}
])
我们使用$filter
删除投影数组中的所有null
值。
在问题中的文件中,这会给你:
{
"_id" : "Bar Tender",
"count" : 1.0
}
{
"_id" : "Waiter",
"count" : 1.0
}
{
"_id" : "Cashier",
"count" : 2.0
}
{
"_id" : "Cook",
"count" : 1.0
}