An example of using Golang Mongodb fuzzy queries

  • 2020-06-19 10:32:23
  • OfStack

preface

In everyday Mongodb, there is a feature called fuzzy queries (using regular matching), such as:


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

This is the way we often use the Mongodb command line, but doing something similar in mgo seems impossible:


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

We use this way to query, can query to calculate my loss!

The following is a summary of the ways to use honesty:

On the command line of Mongodb, we can use the form \abcd\ as our pattern, but in mgo we pass in a string directly, meaning "\a" instead of \a\.

According to point 1, we will change the code 1.


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

But we will find that we still can't get the result we want, then the second point will be produced!

To use fuzzy queries in mgo, one of the structures in mgo is required: 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
}

Then our final code is:


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

conclusion


Related articles: