Hello I have the following code in my golang:
Please take a look:
type User struct {
Id int `json:"id" bson:"_id"`
FirstName string `json:"first_name" bson:"first_name"`
LastName string `json:"last_name" bson:"last_name"`
EmailId string `json:"email_id" bson:"email_id"`
Password string `json:"password" bson:"password"`
PhoneNumber string `json:"phone_number" bson:"phone_number"`
AltPhoneNumber string `json:"alt_phone_number" bson:"alt_phone_number"`
Gender string `json:"gender" bson:"gender"`
Note string `json:"note" bson:"note"`
Address string `json:"address" bson:"address"`
AptNo string `json:"apt_no" bson:"apt_no"`
City string `json:"city" bson:"city"`
Zipcode string `json:"zipcode" bson:"zipcode"`
}
query := bson.M{ "role" : "customer",
"status" : 1,
"$or": []bson.M{
bson.M{"first_name":bson.RegEx{".*"+keyword+"*.", "i"} },
bson.M{"last_name": bson.RegEx{".*"+keyword+"*.", "i"} },
bson.M{"email_id": bson.RegEx{".*"+keyword, "i"} },
bson.M{"phone_number": bson.RegEx{".*"+keyword, "i"} },
bson.M{"alt_phone_number": bson.RegEx{".*"+keyword, "i"} },
}}
err = c.Find(query).All(&result)
I have a record in database with first name "swati" and last name "sharma". When I search "swati" then it works properly, similarly when I search "sharma" it works properly.
Issue is when I search "swati sharma" then it does not return any result. Can anybody tell how I can achieve this output?
&bson.RegEx{Pattern: fmt.Sprintf(".*%s*.", keyword), Options: "i"}also test your regex using regex101.com Notice my regex is a pointer.&. I usefmt.Sprintfbecause concatenations are harder to read and easier to mess up (my opinion) You may also want to break up your logic and test.. for instance make a query just using your original logicbson.M{"first_name":bson.RegEx{".*"+keyword+"*.", "i"} }don't complicate it with the or, status, or role. Isolate and test your regex first - reticentroot