我试图在集合中分组数据后获得特定格式的输出。
集合中的数据如下所示:
[
{
"country": "UK",
"business": "computer",
"companies": 24
},
{
"country": "UK",
"business": "automotive",
"companies": 12
},
{
"country": "US",
"business": "medical",
"companies": 3
},
{
"country": "US",
"business": "food",
"companies": 53
}
]
我已经使用以下聚合来根据
business
对country
进行分组:
[
{
$group: {
_id: "$country",
business: {
$addToSet: "$business"
}
}
}
]
我得到以下结果:
[
{
"_id": "UK",
"business": [ "computer", "automotive" ]
},
{
"_id": "US",
"business": [ "food", "medical" ]
}
]
我的问题:如何使用管道并将输出格式化为如下内容?
[
{
"US": {
"business":[ "food", "medical" ]
}
},
{
"UK": {
"business":[ "computer", "automotive" ]
}
}
]
一个选择是使用
$arrayToObject
:
db.collection.aggregate([
{
$group: {
_id: "$country",
business: {
$addToSet: "$business"
}
}
},
{
$project: {
_id: 0,
res: [
{
k: "$_id",
v: {
business: "$business"
}
}
]
}
},
{
$replaceRoot: {
newRoot: {
"$arrayToObject": "$res"
}
}
}
])