MongoDB - 正則表示式



正則表示式在所有語言中都經常用於在任何字串中搜索模式或單詞。MongoDB 還提供了使用$regex運算子進行字串模式匹配的正則表示式功能。MongoDB 使用 PCRE(Perl 相容正則表示式)作為正則表示式語言。

與文字搜尋不同,我們不需要進行任何配置或命令來使用正則表示式。

假設我們在名為posts的資料庫中插入了一個文件,如下所示:

> db.posts.insert(
{
   "post_text": "enjoy the mongodb articles on tutorialspoint",
   "tags": [
      "mongodb",
      "tutorialspoint"
   ]
}
WriteResult({ "nInserted" : 1 })

使用正則表示式

以下正則表示式查詢搜尋包含字串tutorialspoint的所有帖子:

> db.posts.find({post_text:{$regex:"tutorialspoint"}}).pretty()
{
	"_id" : ObjectId("5dd7ce28f1dd4583e7103fe0"),
	"post_text" : "enjoy the mongodb articles on tutorialspoint",
	"tags" : [
		"mongodb",
		"tutorialspoint"
	]
}
{
	"_id" : ObjectId("5dd7d111f1dd4583e7103fe2"),
	"post_text" : "enjoy the mongodb articles on tutorialspoint",
	"tags" : [
		"mongodb",
		"tutorialspoint"
	]
}
>

同樣的查詢也可以寫成:

>db.posts.find({post_text:/tutorialspoint/})

使用不區分大小寫的正則表示式

為了使搜尋不區分大小寫,我們使用$options引數,其值為$i。以下命令將查詢包含單詞tutorialspoint的字串,無論大小寫如何:

>db.posts.find({post_text:{$regex:"tutorialspoint",$options:"$i"}})

從該查詢返回的結果之一是以下文件,其中包含不同大小寫的單詞tutorialspoint

{
   "_id" : ObjectId("53493d37d852429c10000004"),
   "post_text" : "hey! this is my post on TutorialsPoint", 
   "tags" : [ "tutorialspoint" ]
} 
 

對陣列元素使用正則表示式

我們也可以在陣列欄位上使用正則表示式的概念。當我們實現標籤的功能時,這尤其重要。因此,如果您想搜尋所有具有以單詞 tutorial 開頭的標籤(tutorial 或 tutorials 或 tutorialpoint 或 tutorialphp)的帖子,您可以使用以下程式碼:

>db.posts.find({tags:{$regex:"tutorial"}})

最佳化正則表示式查詢

  • 如果文件欄位已索引,則查詢將使用索引值來匹配正則表示式。與正則表示式掃描整個集合相比,這使得搜尋速度非常快。

  • 如果正則表示式是字首表示式,則所有匹配項都必須以某個字串字元開頭。例如,如果正則表示式為^tut,則查詢必須搜尋僅以tut開頭的字串。

廣告