正則表達(dá)式在所有語(yǔ)言中都經(jīng)常用于搜索任何字符串中的模式或單詞。MongoDB 還使用 $regex 運(yùn)算符為字符串模式匹配提供了正則表達(dá)式的功能。MongoDB 使用 PCRE (Perl 兼容正則表達(dá)式)作為正則表達(dá)式語(yǔ)言。
與文本搜索不同,我們不需要進(jìn)行任何配置或命令即可使用正則表達(dá)式。
假設(shè)我們已經(jīng)在名為 posts 的數(shù)據(jù)庫(kù)中插入了一個(gè)文檔,如下所示
> db.posts.insert( { "post_text": "enjoy the mongodb articles on nhooo", "tags": [ "mongodb", "nhooo" ] } WriteResult({ "nInserted" : 1 })
下面的regex查詢搜索包含字符串 nhooo 的所有帖子–
> db.posts.find({post_text:{$regex:"nhooo"}}).pretty(){ "_id" : ObjectId("5dd7ce28f1dd4583e7103fe0"), "post_text" : "enjoy the mongodb articles on nhooo", "tags" : [ "mongodb", "nhooo" ] } { "_id" : ObjectId("5dd7d111f1dd4583e7103fe2"), "post_text" : "enjoy the mongodb articles on nhooo", "tags" : [ "mongodb", "nhooo" ] } >
相同的查詢也可以寫成-
>db.posts.find({post_text:/nhooo/})
為了使搜索不區(qū)分大小寫,我們使用$options
帶有value的參數(shù)$i
。以下命令將查找?guī)в袉卧~的字符串nhooo
,而不考慮大小寫或小寫字母-
>db.posts.find({post_text:{$regex:"nhooo",$options:"$i"}})
該查詢返回的結(jié)果之一是以下文檔,其中包含nhooo
在不同情況下的單詞-
{ "_id" : ObjectId("53493d37d852429c10000004"), "post_text" : "hey! this is my post on nhooo", "tags" : [ "nhooo" ] }
我們還可以在數(shù)組字段上使用正則表達(dá)式的概念。當(dāng)我們實(shí)現(xiàn)標(biāo)簽的功能時(shí),這尤其重要。因此,如果您要搜索所有帶有標(biāo)簽的單詞,它們都以單詞tutorial(教程或tutorialpoint或tutorialphp)開頭,則可以使用以下代碼-
>db.posts.find({tags:{$regex:"tutorial"}})
如果document字段為indexed
,則查詢將使用索引值來(lái)匹配正則表達(dá)式。與正則表達(dá)式掃描整個(gè)集合相比,這使搜索非???。
如果正則表達(dá)式為prefix expression
,則所有匹配項(xiàng)均應(yīng)以某個(gè)字符串字符開頭。例如,如果regex表達(dá)式為^tut
,則查詢必須僅搜索以開頭的那些字符串tut
。