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

如何在MongoDB中移除指定字段值中@符号前的子字符串?

解决MongoDB移除EmailSuffix字段@前内容的问题

你的代码问题分析

  • $split的分隔符错误使用了"?",实际应该按@分割字符串
  • 即使修正分隔符,你取doc.EmailSuffix[0]会得到@之前的内容,和需求完全相反
  • 代码存在语法错误:forEach的闭合括号缺失,末尾有多余的反引号

正确实现方法

推荐直接用updateMany配合聚合管道更新,无需先聚合再循环,效率更高:

方法1:分割拼接法

db.collection.updateMany(
  { EmailSuffix: { $regex: /.+@/ } }, // 匹配包含@的目标字段
  [
    {
      $set: {
        EmailSuffix: {
          $concat: [
            "@",
            { $arrayElemAt: [ { $split: [ "$EmailSuffix", "@" ] }, 1 ] }
          ]
        }
      }
    }
  ]
)

方法2:正则替换法(MongoDB 4.4+支持)

db.collection.updateMany(
  { EmailSuffix: { $regex: /.+@/ } },
  [
    {
      $set: {
        EmailSuffix: {
          $replaceOne: {
            input: "$EmailSuffix",
            find: /^.+@/, // 匹配从开头到@的所有字符
            replacement: "@" // 替换为@
          }
        }
      }
    }
  ]
)

执行后效果

目标文档会变为:

{
  Name: "Peter",
  Email: "peter@mail.com",
  EmailSuffix: "@mail.com"
}

内容的提问来源于stack exchange,提问作者John T.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:35:22