Golang mgo 模糊查詢的使用
在日常使用的Mongodb中,有一項功能叫做模糊查詢(使用正則匹配),例如:
db.article.find({"title": {$regex: /a/, $options: "im"}})
這是我們常用Mongodb的命令列使用的方式,但是在mgo中做出類似的方式視乎是行不通的:
query := bson.M{"title": bson.M{"$regex": "/a/", "$options": "im"}}
大家用這個方式去查詢,能查詢到算我輸!
下面總結一下,正真使用的方式:
- 在Mongodb的命令列中,我們可以使用形如 \abcd\ 的方式來作為我們的pattern,但是在mgo是直接傳入字串來進行的,也就是傳入的是"\a",而不是\a\。
根據第一點,我們將程式碼修改一下。
query := bson.M{"title": bson.M{"$regex": "a", "$options": "im"}}
但是我們會發現依然不能得到我們想要的結果,那麼第二點就會產生了!
- 在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"}}}