MongoDB Regex

來源:互聯網
上載者:User

標籤:

Regex是使用單個字串來描述、匹配一系列符合某個句法規則的字串。

許多程式設計語言都支援利用Regex進行字串操作。

MongoDB 使用 $regex 操作符來設定匹配字串的Regex。

MongoDB使用PCRE (Perl Compatible Regular Expression) 作為Regex語言。

不同於全文檢索索引,我們使用Regex不需要做任何配置。

考慮以下 posts 集合的文檔結構,該文檔包含了文章內容和標籤:

{   "post_text": "enjoy the mongodb articles on tutorialspoint",   "tags": [      "mongodb",      "tutorialspoint"   ]}
使用Regex

以下命令使用Regex尋找包含 w3cschool.cc 字串的文章:

>db.posts.find({post_text:{$regex:"w3cschool.cc"}})

以上查詢也可以寫為:

>db.posts.find({post_text:/w3cschool.cc/})
不區分大小寫Regex

如果檢索需要不區分大小寫,我們可以設定 $options 為 $i。

以下命令將尋找不區分大小寫字串 w3cschool.cc:

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

集合中會返回所有包含字串 w3cschool.cc 的資料,且不區分大小寫:

{   "_id" : ObjectId("53493d37d852429c10000004"),   "post_text" : "hey! this is my post on  W3Cschool.cc",    "tags" : [ "tutorialspoint" ]}
數組元素使用Regex

我們還可以在數組欄位中使用Regex來尋找內容。 這在標籤的實現上非常有用,如果你需要尋找包含以 tutorial 開頭的標籤資料(tutorial 或 tutorials 或 tutorialpoint 或 tutorialphp), 你可以使用以下代碼:

>db.posts.find({tags:{$regex:"tutorial"}})
最佳化Regex查詢
  • 如果你的文檔中欄位設定了索引,那麼使用索引相比於Regex匹配尋找所有的資料查詢速度更快。

     

  • 如果Regex是首碼運算式,所有匹配的資料將以指定的前置詞字元串為開始。例如: 如果Regex為 ^tut ,查詢語句將尋找以 tut 為開頭的字串。

這裡面使用Regex有兩點需要注意:

Regex中使用變數。一定要使用eval將組合的字串進行轉換,不能直接將字串拼接後傳入給運算式。否則沒有報錯資訊,只是結果為空白!執行個體如下:

var name=eval("/" + 變數值key +"/i");

以下是模糊查詢包含title關鍵詞, 且不區分大小寫:

title:eval("/"+title+"/i")    // 等同於 title:{$regex:title,$Option:"$i"}   

MongoDB Regex

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.