正則表達(dá)式在所有語言當(dāng)中都是經(jīng)常會用到的一個功能,可以用來搜索模式或字符串中的單詞。MongoDB 也提供了這一功能,使用 $regex 運(yùn)算符來匹配字符串模式。MongoDB 使用 PCRE(可兼容 Perl 的正則表達(dá)式)作為正則表達(dá)式語言。
與文本搜索不同,使用正則表達(dá)式不需要使用任何配置或命令。
假如 posts 集合有下面這個文檔,它包含著帖子文本及其標(biāo)簽。
{
"post_text": "enjoy the mongodb articles on tutorialspoint",
"tags": [
"mongodb",
"tutorialspoint"
]
}
使用下列正則表達(dá)式來搜索包含 tutorialspoint 的所有帖子。
>db.posts.find({post_text:{$regex:"tutorialspoint"}})
同樣的查詢也可以寫作下列形式:
>db.posts.find({post_text:/tutorialspoint/})
要想使搜索不區(qū)分大小寫,使用 $options 參數(shù)和值 $i。下列命令將搜索包含 “tutorialspoint” 的字符串,不區(qū)分大小寫。
>db.posts.find({post_text:{$regex:"tutorialspoint",$options:"$i"}})
該查詢返回的一個結(jié)果文檔中含有不同大小寫的 “tutorialspoint” 文本。
{
"_id" : ObjectId("53493d37d852429c10000004"),
"post_text" : "hey! this is my post on TutorialsPoint",
"tags" : [ "tutorialspoint" ]
}
我們還可以在數(shù)組字段上使用正則表達(dá)式。在實(shí)現(xiàn)標(biāo)簽的功能時,這尤為重要。假如想搜索標(biāo)簽以 “tutorial” 開始(tutorial、tutorials、tutorialpoint 或 tutorialphp)的帖子,可以使用下列代碼:
>db.posts.find({tags:{$regex:"tutorial"}})