在 SQL 中我可以做到
UPPER(REPLACE(field.name, ' ', '')) LIKE '%" . $input . "%'
这将删除空格,并将字符串转换为大写,然后再与 $input 进行比较。
有没有办法用 mongodb 来做到这一点?
最佳答案
我知道的唯一方法是使用 $where Queries 。考虑下面的例子:
首先插入一些测试数据
db.likecoll.insert({"name" : "John Smith"})
db.likecoll.insert({"name" : "Jo hn Smith "})
db.likecoll.insert({"name" : "JohnSmith"})
db.likecoll.insert({"name" : "JohnNOSmith"})
然后运行此查询以动态替换名称字段的空格
db.likecoll.find({"$where" : "return this.name.replace(new RegExp(' ', 'g'), '') == 'JohnSmith'" })
结果是
{ "_id" : ObjectId("52f5459eb08622ca2b16ede9"), "name" : "John Smith" }
{ "_id" : ObjectId("52f545adb08622ca2b16edea"), "name" : "Jo hn Smith " }
{ "_id" : ObjectId("52f545b8b08622ca2b16edeb"), "name" : "JohnSmith" }
这应该对您有用,但我个人不喜欢这种方法,主要是因为与可以用索引覆盖的查询相比,这很慢。然而,对于您的 SQL 服务器查询来说也是如此。
编辑:
要将字符串转换为大写,请使用 str.toUpperCase()
JavaScript 函数。
希望对你有帮助!
有一个针对此的功能请求:https://jira.mongodb.org/browse/SERVER-829
关于javascript - 是否有 mongo 替换方法/运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21633848/