Regex 删除MongoDB集合中字符串字段值中的所有空格
我有一个名为“Regex 删除MongoDB集合中字符串字段值中的所有空格,regex,mongodb,replace,collections,mongodb-query,Regex,Mongodb,Replace,Collections,Mongodb Query,我有一个名为“users”的mongodb集合,有几千个用户。由于缺少验证,用户可以创建带有空格的“用户名”。即,用户能够创建用户名,如“我是最好的”或“我是最好的”或“我是最好的”等。由于“用户名”字段在系统中没有以任何形式使用,所以直到现在它还可以 从现在起,客户机希望最后使用“username”字段,也就是说,创建URL,例如https://example.com/profile/{username}” 问题在于“username”字段值的开头、中间和结尾都有空格,如上图所示。因此,我想使
users
”的mongodb集合,有几千个用户。由于缺少验证,用户可以创建带有空格的“用户名”
。即,用户能够创建用户名,如“我是最好的
”或“我是最好的
”或“我是最好的
”等。由于“用户名”字段在系统中没有以任何形式使用,所以直到现在它还可以
从现在起,客户机希望最后使用“username”字段,也就是说,创建URL,例如https://example.com/profile/{username}”
问题在于“username”字段值的开头、中间和结尾都有空格,如上图所示。因此,我想使用查询删除它们
我可以使用以下方式列出所有用户:
db.users.find({username:{ "$regex" : ".*[^\S].*" , "$options" : "i"}}).pretty();
删除用户名字段中的所有空格并将其保存回去的最佳方法是什么?我不知道如何在单个查询中更新它们
谢谢你的帮助
另外,在检查“现有”用户名时,我实际上需要编写一个代码块来替换这些用户名,这样就不会有重复的用户名,但如果需要使用mongodb查询,我仍然想知道我是如何做到的
问题在于“username”字段值的开头、中间和结尾都有空格,如上图所示。因此,我想使用查询删除它们
MongoDB 4.4或更高版本:
您可以从MongoDB 4.2开始使用
- 从MongoDB 4.4开始
- 它将找到空白并替换为空白
MongoDB 4.2或更高版本: 您可以从MongoDB 4.2开始使用
删除左右两侧的空白$trim
按空格和结果数组拆分$split
用户名
迭代上述分割结果的循环$reduce
至concat$concat
用户名
MongoDB 3.6或以上版本:
查找所有用户并循环使用forEach
若要应用图案以删除空白,可以根据需要更新图案replace
更新updateOne
username
不幸的是,该网站正在使用Mongo3.6,我们没有升级的计划yet@ArvindK最后一个选项解决了你的问题吗?是的,它解决了@turivishal,我想说声谢谢!我以为是我干的,但我没有。投票支持这个!
db.users.update(
{ username: { $regex: " " } },
[{
$set: {
username: {
$replaceAll: {
input: "$username",
find: " ",
replacement: ""
}
}
}
}],
{ multi: true }
)
db.users.update(
{ username: { $regex: " " } },
[{
$set: {
username: {
$reduce: {
input: { $split: [{ $trim: { input: "$username" } }, " "] },
initialValue: "",
in: { $concat: ["$$value", "$$this"] }
}
}
}
}],
{ multi: true }
)
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 } });
})