zoukankan      html  css  js  c++  java
  • 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"}}}
    
  • 相关阅读:
    微软API集
    如何在Visual Studio.net中让同一解决方案中包含多个不同类型的项目并共享同一命名空间
    总结:Asp.net页面之间传递参数的几种方法
    Javascript 鼠标滑过显示大图的效果
    HttpContext.Current.Session["key"]取值
    数字金额转大写
    整合多个图片到一个pdf
    .net reflector & disassembler
    yacc grammar for a simple shell
    Windows cmd编码
  • 原文地址:https://www.cnblogs.com/daryl-blog/p/11003078.html
Copyright © 2011-2022 走看看