Golang mgo 模糊查詢的使用

在日常使用的Mongodb中,有一項(xiàng)功能叫做模糊查詢(使用正則匹配),例如:

db.article.find({"title": {$regex: /a/, $options: "im"}})

這是我們常用Mongodb的命令行使用的方式,但是在mgo中做出類似的方式視乎是行不通的:

query := bson.M{"title": bson.M{"$regex": "/a/", "$options": "im"}}

大家用這個(gè)方式去查詢,能查詢到算我輸!
下面總結(jié)一下,正真使用的方式:

  1. 在Mongodb的命令行中,我們可以使用形如 \abcd\ 的方式來(lái)作為我們的pattern,但是在mgo是直接傳入字符串來(lái)進(jìn)行的,也就是傳入的是"\a",而不是\a\。

根據(jù)第一點(diǎn),我們將代碼修改一下。

query := bson.M{"title": bson.M{"$regex": "a", "$options": "im"}}

但是我們會(huì)發(fā)現(xiàn)依然不能得到我們想要的結(jié)果,那么第二點(diǎn)就會(huì)產(chǎn)生了!

  1. 在mgo中要用到模糊查詢需要mgo中自帶的一個(gè)結(jié)構(gòu): bson.RegEx
// RegEx represents a regular expression.  The Options field may contain
// individual characters defining the way in which the pattern should be
// applied, and must be sorted. Valid options as of this writing are 'i' for
// case insensitive matching, 'm' for multi-line matching, 'x' for verbose
// mode, 'l' to make \w, \W, and similar be locale-dependent, 's' for dot-all
// mode (a '.' matches everything), and 'u' to make \w, \W, and similar match
// unicode. The value of the Options parameter is not verified before being
// marshaled into the BSON format.
type RegEx struct {
    Pattern string
    Options string
}

那么最終我們的代碼為:

query := bson.M{"title": bson.M{"$regex": bson. RegEx:{Pattern:"/a/", Options: "im"}}}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容