Golang mgo 模糊查詢的使用


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

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

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

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

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

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

根據第一點,我們將代碼修改一下。

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

但是我們會發現依然不能得到我們想要的結果,那么第二點就會產生了!

  1. 在mgo中要用到模糊查詢需要mgo中自帶的一個結構: 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"}}}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM