2011-11-23 81 views
27

我在Mongo中使用了不區分大小寫的搜索,類似於https://stackoverflow.com/q/5500823/1028488在Mongo中區分大小寫的搜索

即我正在使用正則表達式與選項我。但我在時遇到限制的正則表達式,只是這個詞,它的執行更像是一個「喜歡」在SQL

例如:如果我使用的查詢像 {"SearchWord" : { '$regex' : 'win', $options: '-i' }},它讓我看到結果的勝利,窗口&冬天。我如何限制它只是顯示勝利?

我試過/^win$/,但它的無效Json ....請建議一種方式。

在此先感謝

回答

17

UPDATE:由於MongoDB的2.4的人會使用「文本」索引和全文搜索查詢來做到這一點。你可以閱讀關於他們here。如果使用最近的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" } 

然而,你的版本是行不通的,因爲你不需要「/」 S時使用正則表達式$操作:

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

請注意,不區分大小寫查詢不使用索引所以它可能是有意義的做一個小寫的搜索內容字段,這樣可以加快該查詢了。

轉到here對RegularExpressions

+1

$文本不是正則表達式的替代品。這是相當嚴格的,不會讓他找到「勝利」的「冬季」。 –

+0

@BT你說得對。爲了做到這一點,人們必須存儲n-gram並且匹配那些。 [使用MongoDB和Python進行模糊搜索](https://medium.com/xeneta/fuzzy-search-with-mongodb-and-python-57103928ee5d#.yg7f3428b) – Rohmer

+0

另請參見:[不區分大小寫的索引](https:// docs .mongodb.com/manual/core/index-case-insensitive /) – Rohmer

-1

不區分大小寫 db.users.find更多信息({ 「名」:{$正則表達式:新的RegExp( 「VI」, 「我」)}})

對於區分大小寫 db.users.find({ 「名」: 「六」}) 或 db.users.find({ 「電子郵件」: 「[email protected]」})

搜索在用戶表中

name is co列名和搜索到的「Vi」文本

57

您可以使用$options => i進行不區分大小寫的搜索。給出一些字符串匹配所需的可能示例。

精確區分大小寫string

db.collection.find({name:{'$regex' : '^string$', '$options' : 'i'}}) 

包含string

db.collection.find({name:{'$regex' : 'string', '$options' : 'i'}}) 

開始string

db.collection.find({name:{'$regex' : '^string', '$options' : 'i'}}) 

末與string

db.collection.find({name:{'$regex' : 'string$', '$options' : 'i'}}) 

不包含string

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

保持這個爲書籤,以及您可能需要的任何其他改變的參考。 http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/

+0

錯誤地,您已將「包含字符串」的示例放在「確切的不區分大小寫的字符串」中,反之亦然。我通過交換這兩個案例的例子來編輯你的答案,並糾正了一些語法錯誤。 – gauravparmar

+0

@gauravparmar:請檢查並糾正是否有錯誤。 –

+0

我已經編輯了你的答案,但它必須經過同行評議,它說。 – gauravparmar