Mongo中不区分大小写的搜索

Pra*_*eta 56 regex case-insensitive pattern-matching match mongodb

我在Mongo中使用不区分大小写的搜索,类似于/sf/ask/385057641/.

即我正在使用带有选项的正则表达式i.但是我在将正则表达式限制为该单词时遇到了麻烦,它在SQL中的表现更像"喜欢"

例如:如果我使用查询 {"SearchWord" : { '$regex' : 'win', $options: '-i' }},它会显示win,window和winter的结果.我如何将其限制为jsut show win?

我试过了,/^win$/但它说无效Json ....请建议一个方法.

提前致谢

Som*_*luk 102

您可以使用$options => i不区分大小写的搜索.提供字符串匹配所需的一些可能示例.

确切的不区分大小写 string

db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}})
Run Code Online (Sandbox Code Playgroud)

包含 string

db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}})
Run Code Online (Sandbox Code Playgroud)

从...开始 string

db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}})
Run Code Online (Sandbox Code Playgroud)

结束 string

db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}})
Run Code Online (Sandbox Code Playgroud)

不包含 string

db.collection.find({name:{'$regex' : '^((?!string).)*$', '$options' : 'i'}})
Run Code Online (Sandbox Code Playgroud)

将此作为书签,以及您可能需要的任何其他更改的参考. http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/


Alp*_*haB 53

你可以使用'$regex':'^win$'/^win$/i(注意第二个没有引用)

来源:与Mongo的查询中的正则表达式


Tyl*_*ock 19

更新:从MongoDB 2.4开始,人们将使用"文本"索引和全文搜索查询来执行此操作.你可以在这里阅读它们.如果使用最近的MongoDB,下面的方法将是愚蠢和不必要的.

但是,如果你有MongoDB <2.4.0,你可以像这样使用正则表达式:

> db.reg.insert({searchword: "win"})
> db.reg.insert({searchword: "window"})
> db.reg.insert({searchword: "Win"})

> db.reg.find()
{ "_id" : ObjectId("4ecd2e33dd68c9021e453d12"), "searchword" : "win" }
{ "_id" : ObjectId("4ecd2e36dd68c9021e453d13"), "searchword" : "window" }
{ "_id" : ObjectId("4ecd2e39dd68c9021e453d14"), "searchword" : "Win" }

> db.reg.find({ searchword: /^win$/i })
{ "_id" : ObjectId("4ecd2e33dd68c9021e453d12"), "searchword" : "win" }
{ "_id" : ObjectId("4ecd2e39dd68c9021e453d14"), "searchword" : "Win" }
Run Code Online (Sandbox Code Playgroud)

但是,由于在使用$ regex运算符时不需要"/",因此您的版本无法正常工作:

> db.reg.find({ searchword: { $regex: "^win$", $options: '-i' }})
{ "_id" : ObjectId("4ecd2e33dd68c9021e453d12"), "searchword" : "win" }
{ "_id" : ObjectId("4ecd2e39dd68c9021e453d14"), "searchword" : "Win" }
Run Code Online (Sandbox Code Playgroud)

请注意,不区分大小写的查询不使用索引,因此创建小写的搜索字段可能是有意义的,这样您就可以加快查询速度.

在这里对RegularExpressions更多信息

  • $text 不是正则表达式的替代品。这是非常严格的,不允许他通过搜索“win”来找到“winter”。 (2认同)