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

如何用MongoDB聚合将数组内的逗号分隔字符串拆分为独立元素?

解决方案

你的需求可以通过MongoDB聚合中的$arrayElemAt和$split操作符组合实现,具体聚合管道如下:

db.yourCollectionName.aggregate([
  {
    $set: {
      Names: {
        $split: [ { $arrayElemAt: [ "$Names", 0 ] }, "," ]
      }
    }
  }
])

代码说明

  1. $arrayElemAt: [ "$Names", 0 ]:提取Names数组中的第一个元素(即逗号分隔的字符串 "abc,xyz,qwerty")
  2. $split: [ ..., "," ]:将提取到的字符串按逗号分隔,拆分为新数组 ["abc", "xyz", "qwerty"]
  3. $set:将拆分后的新数组重新赋值给Names字段,覆盖原数组

扩展情况(若Names数组含多个逗号分隔字符串)

如果Names数组中有多个类似元素(比如["a,b", "c,d"]),可以用$map遍历数组逐个拆分,再合并为一维数组:

db.yourCollectionName.aggregate([
  {
    $set: {
      Names: {
        $reduce: {
          input: { $map: { input: "$Names", as: "item", in: { $split: [ "$$item", "," ] } } },
          initialValue: [],
          in: { $concatArrays: [ "$$value", "$$this" ] }
        }
      }
    }
  }
])

内容的提问来源于stack exchange,提问作者Abhishek S.K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 14:02:28