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

如何在MongoDB聚合框架中将字符串拆分为单个字符的数组

你遇到的报错是因为MongoDB的$split运算符明确要求分隔符不能是空字符串,和JavaScript原生split方法的行为不一致,所以无法直接用$split实现单字符拆分的需求,可根据你使用的MongoDB版本选择以下方案解决:

方案1:MongoDB 3.4及以上版本通用(推荐,性能更高)

利用$strLenCP获取字符串长度,结合$range生成索引数组,再通过$map逐个截取单个字符,不需要开启JavaScript执行权限:

{
  $project:{
    _id:"$_id._id",
    name:"$_id.name",
    array_field:{
      $map: {
        input: { $range: [0, { $strLenCP: "$_id.name" }] },
        in: { $substrCP: ["$_id.name", "$$this", 1] }
      }
    }
  }
}

方案2:MongoDB 4.4及以上版本可用

如果对性能要求不高,也可以用$function直接调用JavaScript的拆分逻辑:

{
  $project:{
    _id:"$_id._id",
    name:"$_id.name",
    array_field:{
      $function: {
        body: function(str) { return str.split(''); },
        args: ["$_id.name"],
        lang: "js"
      }
    }
  }
}

内容的提问来源于stack exchange,提问作者Nick

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:06:05