删除 MongoDB 集合中字符串字段值中的所有空格

Arv*_* K. 5 regex collections replace mongodb mongodb-query

我有一个名为“ users”的 mongodb 集合,有几千个用户。由于缺乏验证,用户能够创建username其中包含空格的“”。即,用户能够创建诸如“ I am the best”或“ I am the best”或“ I am the best ”等用户名。由于“用户名”字段在系统中没有以任何形式使用,所以到目前为止还可以。

从现在开始,客户端最终要使用“username”字段,即制作诸如“https://example.com/profile/{username}”之类的url。

问题是“用户名”字段值的开头、中间和结尾都有空格,如上所示,是随机的。所以我想使用查询删除它们。

我可以使用以下方式列出所有用户:

db.users.find({username:{ "$regex" : ".*[^\S].*" , "$options" : "i"}}).pretty();
Run Code Online (Sandbox Code Playgroud)

删除用户名字段中的所有空格并将其保存回来的最佳方法是什么?我不确定如何在单个查询中更新它们。

感谢帮助!

诗。我实际上需要编写一个代码块来替换这些用户名,同时检查“现有”用户名,以便不存在重复项,但如果我需要使用 mongodb 查询来执行此操作,我仍然想知道如何执行此操作。

tur*_*hal 7

问题是“用户名”字段值的开头、中间和结尾都有空格,如上所示,是随机的。所以我想使用查询删除它们。

MongoDB 4.4 或更高版本:

从 MongoDB 4.2 开始,您可以将更新与聚合管道一起使用,

  • $replaceAll从 MongoDB 4.4 开始
  • 它将找到空白并替换为空白
db.users.update(
  { username: { $regex: " " } },
  [{
    $set: {
      username: {
        $replaceAll: {
          input: "$username",
          find: " ",
          replacement: ""
        }
      }
    }
  }],
  { multi: true }
)
Run Code Online (Sandbox Code Playgroud)

操场


MongoDB 4.2 或更高版本:

从 MongoDB 4.2 开始,您可以将更新与聚合管道一起使用,

  • $trim删除左侧和右侧的空白
  • $splitusername按空间和结果数组分割
  • $reduce迭代上述分割结果的循环
  • $concat连接username
db.users.update(
  { username: { $regex: " " } },
  [{
    $set: {
      username: {
        $reduce: {
          input: { $split: [{ $trim: { input: "$username" } }, " "] },
          initialValue: "",
          in: { $concat: ["$$value", "$$this"] }
        }
      }
    }
  }],
  { multi: true }
)
Run Code Online (Sandbox Code Playgroud)

操场


MongoDB 3.6 或更高版本:

  • find所有用户并循环遍历 forEach
  • replace要应用模式来删除空白,您可以根据您的要求更新模式
  • updateOne更新已更新username
db.users.find({ username: { $regex: " " } }, { username: 1 }).forEach(function(user) {
  let username = user.username.replace(/\s/g, "");
  db.users.updateOne({ _id: user._id }, { $set: { username: username } });
})
Run Code Online (Sandbox Code Playgroud)