【问题标题】:Removing all spaces in a string field value in a MongoDB collection删除 MongoDB 集合中字符串字段值中的所有空格
【发布时间】:2021-08-01 19:53:54
【问题描述】:

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

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

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

我可以列出所有用户:

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

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

感谢您的帮助!

附言。我实际上需要编写一个代码块来替换这些用户名,同时检查“现有”用户名,以免重复,但如果我需要使用 mongodb 查询,我仍然想知道我是如何做到的。

【问题讨论】:

    标签: regex mongodb replace collections mongodb-query


    【解决方案1】:

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

    MongoDB 4.4 或更高版本:

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

    • $replaceAll 从 MongoDB 4.4 开始
    • 它将找到空白并替换为空白
    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 删除左右两边的空白
    • $split 按空格和结果数组拆分 username
    • $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 应用模式去除空白,您可以根据需要更新模式
    • 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 } });
    })
    

    【讨论】:

      猜你喜欢
      • 2012-01-06
      • 2019-11-25
      • 1970-01-01
      • 1970-01-01
      • 2013-10-20
      • 1970-01-01
      相关资源
      最近更新 更多