我有这个聚合函数:
[{
$group: {
_id: {
rl: "$rl",
status: "$screener_status"
},
total: {
$sum: 1
}
}
},
{
$project: {
_id: 0,
rl: "$_id.rl",
status: "$_id.status",
total: "$total"
}
}
])
哪个将返回此数据集:
{ "rl" : "200", "status" : "terminate", "total" : 1 }
{ "rl" : "200", "status" : "in_progress", "total" : 1 }
{ "rl" : "200", "status" : "security_terminate", "total" : 1 }
我想把它变成一个像这样的对象:
{
"rl": "200",
"status": {
"terminate": 1,
"in_progress": 1,
"security_terminate": 1
}
}
或者至少与此类似。最后,我尝试使用不同的组,但是没有尝试过
答案 0 :(得分:0)
您可以使用$arrayToObject
:
[
{$group: {
_id: {rl: '$rl', status: '$screener_status'},
total: {$sum: 1}
}},
{$group: {
_id: '$_id.rl',
pairs: {$push: {k: '$_id.status', v: '$total'}}
}},
{$project: {
_id: 0,
rl: '$_id',
status: {$arrayToObject: '$pairs'}
}}
]
能为您带来确切的结果:
{
"rl" : "200",
"status" : {
"security_terminate" : 1.0,
"in_progress" : 1.0,
"terminate" : 1.0
}
}