Golang Mongodb模糊查询的使用示例

发布时间:2022-04-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了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\。

根据第一点,我们将代码修改一下。

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本宝典的支持。

脚本宝典总结

以上是脚本宝典为你收集整理的Golang Mongodb模糊查询的使用示例全部内容,希望文章能够帮你解决Golang Mongodb模糊查询的使用示例所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:golanggolang