Golang Mongodb模糊查詢的使用示例
前言
在日常使用的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\。
根據(jù)第一點,我們將代碼修改一下。
query := bson.M{"title": bson.M{"$regex": "a", "$options": "im"}}
但是我們會發(fā)現(xiàn)依然不能得到我們想要的結果,那么第二點就會產生了!
在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"}}}
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
- golang操作mongodb的方法
- Golang對MongoDB數(shù)據(jù)庫的操作簡單封裝教程
- golang中使用mongo的方法介紹
- golang 連接mongoDB的方法示例
- mongodb官方的golang驅動基礎使用教程分享
- 利用golang驅動操作MongoDB數(shù)據(jù)庫的步驟
- 詳解Golang使用MongoDB通用操作
- golang連接MongoDB數(shù)據(jù)庫及數(shù)據(jù)庫操作指南
- Golang對mongodb進行聚合查詢詳解
- Go語言學習筆記之golang操作MongoDB數(shù)據(jù)庫
- Golang實現(xiàn)Mongo數(shù)據(jù)庫增刪改查操作
相關文章
Go語言使用goroutine及通道實現(xiàn)并發(fā)詳解
這篇文章主要為大家介紹了Go語言使用goroutine及通道實現(xiàn)并發(fā)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08
GoLang并發(fā)機制探究goroutine原理詳細講解
goroutine是Go語言提供的語言級別的輕量級線程,在我們需要使用并發(fā)時,我們只需要通過 go 關鍵字來開啟 goroutine 即可。這篇文章主要介紹了GoLang并發(fā)機制goroutine原理,感興趣的可以了解一下2022-12-12
golang?使用sort.slice包實現(xiàn)對象list排序
這篇文章主要介紹了golang?使用sort.slice包實現(xiàn)對象list排序,對比sort跟slice兩種排序的使用方式區(qū)別展開內容,需要的小伙伴可以參考一下2022-03-03

