【发布时间】:2014-02-07 17:14:03
【问题描述】:
在 SQL 中我可以做到
UPPER(REPLACE(field.name, ' ', '')) LIKE '%" . $input . "%'
这将删除空格并将字符串转换为大写,然后再与 $input 进行比较。
有没有办法用 mongodb 做到这一点?
【问题讨论】:
标签: javascript sql mongodb
在 SQL 中我可以做到
UPPER(REPLACE(field.name, ' ', '')) LIKE '%" . $input . "%'
这将删除空格并将字符串转换为大写,然后再与 $input 进行比较。
有没有办法用 mongodb 做到这一点?
【问题讨论】:
标签: javascript sql 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 函数。
希望对你有帮助!
【讨论】: