正則表達式是使用單個字符串來描述、匹配一系列符合某個句法規(guī)則的字符串。
許多程序設計語言都支持利用正則表達式進行字符串操作。
MongoDB 使用 $regex 操作符來設置匹配字符串的正則表達式。
MongoDB使用PCRE (Perl Compatible Regular Expression) 作為正則表達式語言。
不同于全文檢索,我們使用正則表達式不需要做任何配置。
考慮以下 posts 集合的文檔結(jié)構,該文檔包含了文章內(nèi)容和標簽:
{ "post_text": "enjoy the mongodb articles on tutorialspoint", "tags": [ "mongodb", "tutorialspoint" ] }
以下命令使用正則表達式查找包含 w3cschool.cn 字符串的文章:
>db.posts.find({post_text:{$regex:"w3cschool.cn"}})
以上查詢也可以寫為:
>db.posts.find({post_text:/w3cschool.cn/})
如果檢索需要不區(qū)分大小寫,我們可以設置 $options 為 $i。
以下命令將查找不區(qū)分大小寫的字符串 w3cschool.cn:
>db.posts.find({post_text:{$regex:"w3cschool.cn",$options:"$i"}})
集合中會返回所有包含字符串 w3cschool.cn 的數(shù)據(jù),且不區(qū)分大小寫:
{ "_id" : ObjectId("53493d37d852429c10000004"), "post_text" : "hey! this is my post on W3Cschool.cc", "tags" : [ "tutorialspoint" ] }
我們還可以在數(shù)組字段中使用正則表達式來查找內(nèi)容。 這在標簽的實現(xiàn)上非常有用,如果你需要查找包含以 tutorial 開頭的標簽數(shù)據(jù)(tutorial 或 tutorials 或 tutorialpoint 或 tutorialphp), 你可以使用以下代碼:
>db.posts.find({tags:{$regex:"tutorial"}})
更多建議: