A regular query in mongo shell is: find({"name": queryWrod})
, queryWrod
is a string. This is equivalent to this in Golang:
cursor, err := homeSites.Find(context.TODO(), bson.D{{"name", queryWrod}})
A fuzzy(regex) match in mongo shell is: find({"name", /abc/})
, which in Golang we do this:
queryWord := "abc"
query := bson.M{"name": bson.M{"$regex": queryWord, "$options": "im"}}
cursor, err := homeSites.Find(context.TODO(), query)
Full working example:
queryWord := "abc"
query := bson.M{"name": bson.M{"$regex": queryWord, "$options": "im"}}
cursor, err := homeSites.Find(context.TODO(), query)
if err != nil {
log.Println(err)
}
// var sites []bson.M
var sites []models.Site
if err = cursor.All(context.TODO(), &sites); err != nil {
log.Fatal(err)
}
fmt.Println(sites)