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?
I made the following changes in my code and it works.
name := strings.Replace(keyword, " ", "|", -1) conditions := bson.M{ "role" : config.ProviderRole, "status" : status, "$or": []bson.M{ bson.M{"first_name":bson.RegEx{"(?i).*"+name+".*", "i"} }, bson.M{"last_name": bson.RegEx{ "(?i).*"+name+".*", "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)