Golang mgo use fuzzy queries

In Mongodb daily use, there is a feature called fuzzy queries (using regular match), for example:

db.article.find({"title": {$regex: /a/, $options: "im"}})

This is the way we used Mongodb command-line use, but made in a manner similar to the mgo depend not work:

query := bson.M{"title": bson.M{"$regex": "/a/", "$options": "im"}}

We use this way to query, the query can I lose count!
The following summarizes what way are really used:

  1. In Mongodb command line, we can use the form \ abcd way as our pattern, but in mgo is passed directly to a string, which is passed is "\ a", instead of \ a .

    According to the first point, we will modify the code.

query := bson.M{"title": bson.M{"$regex": "a", "$options": "im"}}

But we will find that still can not get the results we want, then the second point will be created!

  1. In the mgo mgo need to use fuzzy queries comes with a structure: 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
}

So ultimately our code is:

query := bson.M{"title": bson.M{"$regex": bson. RegEx:{Pattern:"/a/", Options: "im"}}}

Guess you like

Origin www.cnblogs.com/daryl-blog/p/11003078.html