You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 13:12:14