我从一个聚合组阶段得到了以下输出
[
{
"region": "region1",
"business": "Electronics",
"country": "US"
},
{
"region": "region1",
"business": "Medical",
"country": "US"
},
{
"region": "region1",
"business": "Electronics",
"country": "UK"
},
{
"region": "region2",
"business": "Automotive",
"country": "Japan"
},
{
"region": "region2",
"business": "Food",
"country": "China"
}
]
我想合并输出如下:
[
{
"region": "region1",
"business": [
{ "Electronics": ["UK", "US"] },
{ "Medical": ["US"] }
]
},
{
"region": "region2",
"business": [
{ "Automotive": ["Japan"] },
{ "Food": ["China"] }
]
}
]
我可以在这里使用哪种聚合来动态地进行整合?
1条答案
按热度按时间gopyfrb31#
1.按
region
和business
分组,并将country
推入countries
数组。1.按
region
分组并推送键值对(k:business
,v:countries
)到business
阵列中。1.设置
business
字段以将每个键值对转换为对象并匹配所需的输出。Demo @ Mongo Playground