欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Golang Mongodb模糊查詢的使用示例

 更新時(shí)間:2019年02月26日 08:36:59   作者:siskinc  
這篇文章主要給大家介紹了關(guān)于Golang Mongodb模糊查詢的使用示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

前言

在日常使用的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é)一下,正真使用的方式:

在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)生了!

在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"}}}

總結(jié)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)腳本之家的支持。

相關(guān)文章

最新評(píng)論