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

如何在MongoDB投影中将对象数组转换为字符串?

MongoDB投影中转换数组对象为拼接字符串的实现方法

你可以通过MongoDB聚合框架里的$map和$join操作符组合完成这个转换,具体实现步骤如下:

  1. 用$map遍历healthDetails数组,把每个对象的problem和note字段拼接成「问题 - 备注」格式的字符串
  2. 用$join把$map生成的字符串数组用, (逗号加空格)连接成单个字符串
  3. 在$project阶段将原healthDetails字段替换为处理后的字符串

具体聚合代码

db.collection.aggregate([
  {
    $project: {
      healthDetails: {
        $join: [
          {
            $map: {
              input: "$healthDetails",
              as: "item",
              in: { $concat: ["$$item.problem", " - ", "$$item.note"] }
            }
          },
          ", "
        ]
      }
    }
  }
])

代码说明

  • $map:遍历目标数组,对每个元素(命名为$$item)执行字符串拼接,输出由拼接后的字符串组成的新数组
  • $join:将$map输出的数组元素用指定分隔符连接成完整字符串,最终赋值给healthDetails字段

效果验证

输入文档:

{
  "healthDetails": [
    {
      "problem": "Fever",
      "note": "normal"
    },
    {
      "problem": "Allergy",
      "note": "critical"
    }
  ]
}

执行聚合后输出:

{
  "healthDetails": "Fever - normal, Allergy - critical"
}

内容的提问来源于stack exchange,提问作者Code The World

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 09:37:06