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

Removing all spaces in a string field value in a MongoDB collection

我有一个名为“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();

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

感谢帮助!

Ps。我实际上需要编写一个代码块来替换这些用户名,同时检查“现有”用户名,以便没有重复,但如果我需要使用 mongodb 查询,我仍然想知道我该怎么做。

The problem is this that the "username" field values have spaces at the beginning, middle and at the end as shown above, on random. So I want to remove them using a query.

MongoDB 4.4 或以上:

从MongoDB 4.2开始可以使用update with aggregation pipeline

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

Playground


MongoDB 4.2 或以上:

从MongoDB 4.2开始可以使用update with aggregation pipeline

  • $trim 去除左右两边的白色space
  • $splitusername 拆分为 space 和结果数组
  • $reduce 迭代上述拆分结果的循环
  • $concat 连接 username
db.users.update(
  { username: { $regex: " " } },
  [{
    $set: {
      username: {
        $reduce: {
          input: { $split: [{ $trim: { input: "$username" } }, " "] },
          initialValue: "",
          in: { $concat: ["$$value", "$$this"] }
        }
      }
    }
  }],
  { multi: true }
)

Playground


MongoDB 3.6 或以上:

  • find 所有用户并遍历 forEach
  • replace应用图案去除白色space,您可以根据需要更新图案
  • 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 } });
})