MongoDB GO Driver 实现模糊查询
距离上次更新已有 1645 天,文章内容可能已过时。
MongoDB的模糊查询
模糊查询时数据库应用中不可缺少的一步,MySQL中使用like
和或者regexp
来实现实现模糊查询,而MongoDB则使用$regex
操作符或直接使用正则表达式对象来实现。
MySQL | MongoDB |
---|---|
select * from users where name like ’%gooohlan%’ | db.users.find({name: {$regex: /gooohlan/}}) |
select * from users where name regexp ’gooohlan’ | db.users.find({name: /gooohlan/}) |
更多相关的语法可查看官方文档:$regex,就不再做多讨论。
使用MongoDB GO Driver进行查询
先来看看我们的数据源:
shell
1 | db.users.find({}) |
然后执行模糊查询:
shell
1 | db.users.find({name:{$regex: /gooohlan/,$options: "i"}}) |
错误尝试
上述方式是MongoDB的命令行的执行方式,如果我们直接在Go里面直接这样写是行不通的
go
1 | filter := bson.M{ |
当你兴高采烈地拿着上面的查询条件去查询时,你会发现它会返回一个空数组给你
正确的使用方式
go
1 | filter := bson.M{ |
执行后发现还是没有,一番查找后才发现Pattern
不再额外需要两个/
,直接填写正则内容即可,所以我们改为:
go
1 | filter := bson.M{ |
执行结果为:
shell
1 | {ID:ObjectID("600704fffc9b483f284d0bc3") Name:1gooohlan} |
与命令行查找的一致,说明没有问题
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 顾澜的技术小站!
评论
GitalkValine
Powered By Valine
v1.5.2
v1.5.2