如何通过MongoDB聚合管道生成指定格式的分组输出?
MongoDB聚合管道调整输出格式问题
原始集合数据
[ { "country": "UK", "business": "computer", "companies": 24 }, { "country": "UK", "business": "automotive", "companies": 12 }, { "country": "US", "business": "medical", "companies": 3 }, { "country": "US", "business": "food", "companies": 53 } ]
当前聚合语句及结果
已使用以下聚合语句按country字段分组business:
[ { $group: { _id: "$country", business: { $addToSet: "$business" } } } ]
得到的结果:
[ { "_id": "UK", "business": [ "computer", "automotive" ] }, { "_id": "US", "business": [ "food", "medical" ] } ]
期望输出格式
需要将输出调整为以下样式:
[ { "US": { "business":[ "food", "medical" ] } }, { "UK": { "business":[ "computer", "automotive" ] } } ]
解决方案
在现有聚合管道的基础上,添加$replaceRoot阶段,结合$arrayToObject操作符将分组后的_id转换为文档的顶级键:
[ { $group: { _id: "$country", business: { $addToSet: "$business" } } }, { $replaceRoot: { newRoot: { $arrayToObject: [[{ k: "$_id", v: { business: "$business" } }]] } } } ]
操作说明
$arrayToObject:将包含键值对的数组转换为对象,这里把分组得到的国家名称($_id)作为对象的键(k),包含business数组的对象作为对应的值(v)。$replaceRoot:将转换后的对象替换为当前文档的根结构,最终得到以国家名称为顶级键的输出格式。
内容的提问来源于stack exchange,提问作者m.y.m
相关产品推荐
相关产品推荐

