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

MongoDB中移除字符串中间多余空格的技术实现问题

解决MongoDB字符串中间多余空格的问题

$trim只能移除字符串首尾的空白,没法处理中间的连续空格,所以需要结合其他操作符实现需求,以下两种方案都可行:

方案一:用$replaceAll配合正则表达式

通过正则匹配所有连续空白字符,替换为单个空格,再用$trim确保首尾无空格:

db.collection.find(
  { _id: 3 },
  {
    name: {
      $trim: {
        input: {
          $replaceAll: {
            input: "$name",
            find: /\s+/,
            replacement: " "
          }
        }
      }
    }
  }
)

方案二:用$split+$filter+$join组合

先把字符串按空格拆分成数组,过滤掉数组里的空元素,再用单个空格重新拼接:

db.collection.find(
  { _id: 3 },
  {
    name: {
      $join: {
        input: { 
          $filter: { 
            input: { $split: ["$name", " "] }, 
            cond: { $ne: ["$$this", ""] } 
          } 
        },
        separator: " "
      }
    }
  }
)

两种方法都能得到预期结果:{ "_id" : 3, "name" : "Shyam Lingam" }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 23:48:23