新聞中心

創(chuàng)新互聯(lián)建站是一家專業(yè)提供石樓企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站制作、網(wǎng)站設(shè)計(jì)、成都h5網(wǎng)站建設(shè)、小程序制作等業(yè)務(wù)。10年已為石樓眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)的建站公司優(yōu)惠進(jìn)行中。
與文本搜索不同,您不需要執(zhí)行任何配置或命令就可以直接使用正則表達(dá)式。假設(shè)我們已經(jīng)在名為 posts 的集合中插入了一個(gè)文檔,如下所示:
> db.posts.insert(
... {
... "post_text": "enjoy the mongodb articles on bianchengbang",
... "tags": ["mongodb", "bianchengbang"]
... }
... )
使用正則表達(dá)式
下面的 regex 查詢將搜索 post_text 字段中包含字符串“bianchengbang”的所有文檔:
> db.posts.find({post_text:{$regex:"bianchengbang"}}).pretty()
{
"_id" : ObjectId("6041dfc3835e4aa734b591df"),
"post_text" : "enjoy the mongodb articles on bianchengbang",
"tags" : [
"mongodb",
"bianchengbang"
]
}
上面的查詢也可以寫成如下所示的樣子:
> db.posts.find({post_text:/bianchengbang/}).pretty()
{
"_id" : ObjectId("6041dfc3835e4aa734b591df"),
"post_text" : "enjoy the mongodb articles on bianchengbang",
"tags" : [
"mongodb",
"bianchengbang"
]
}
在不區(qū)分大小寫的情況下使用正則表達(dá)式
若要在查詢時(shí)不區(qū)分大小寫,我們可以將 $options 參數(shù)的值設(shè)置為 $i,下面的命令可以查詢 post_text 字段中包含“bianchengbang”的文檔,且不區(qū)分大小寫。
> db.posts.find({post_text:{$regex:"BianChengBang",$options:"$i"}}).pretty()
{
"_id" : ObjectId("6041dfc3835e4aa734b591df"),
"post_text" : "enjoy the mongodb articles on bianchengbang",
"tags" : [
"mongodb",
"bianchengbang"
]
}
對數(shù)組元素使用正則表達(dá)式
我們還可以在數(shù)組字段上使用正則表達(dá)式來查找內(nèi)容,這在實(shí)現(xiàn)標(biāo)簽時(shí)非常有用。假如要搜索所有以 b 開頭的字段(例如 bian、biancheng、bianchengbang 等),可以使用如下所示的代碼:
> db.posts.find({tags:{$regex:"b"}}).pretty()
{
"_id" : ObjectId("6041dfc3835e4aa734b591df"),
"post_text" : "enjoy the mongodb articles on bianchengbang",
"tags" : [
"mongodb",
"bianchengbang"
]
}
優(yōu)化正則表達(dá)式查詢
如果文檔字段已建立索引,那么查詢將使用索引值來匹配正則表達(dá)式,與使用正則表達(dá)式掃描整個(gè)集合相比,使用索引來查詢數(shù)據(jù)的速度會(huì)更快。
如果正則表達(dá)式是前綴表達(dá)式,則所有匹配項(xiàng)均應(yīng)以某個(gè)字符串字符開頭。例如,如果正則表達(dá)式為 ^tut,則查詢僅需要搜索以 tut 開頭的那些字符串。
網(wǎng)站名稱:MongoDB正則表達(dá)式
分享地址:http://m.fisionsoft.com.cn/article/cojgeoi.html


咨詢
建站咨詢
