例如,有一个 table-collection accounts。
account time category
r1 2020 fact
r1 2020 plan
r3 2019 fact
如何显示帐户+时间分组并显示这样的分组有哪些类别?
这是聚合中的组查询:
{
_id: {
'account': '$account',
'time': '$time',
},
count: { $sum: 1 },
}
数据库输出以下格式的文档:
{
"_id" : {
"account" : "r1",
"time" : "2020"
},
"count" : 2
}
但是如何在那里添加独特的类别呢?对于输出是这样的:
{
"_id" : {
"account" : "r1",
"time" : "2020"
},
"cats": ['fact','plan'],
"count" : 2
},
{
"_id" : {
"account" : "r3",
"time" : "2019"
},
"cats": ['fact'],
"count" : 1
},
您可以使用运算符
$push
:https ://docs.mongodb.com/manual/reference/operator/aggregation/push/ 。