skip to Main Content
query := bson.M{
    "nombre": bson.M{"$regex": `(?i)` + search}, // me va a buscar los nombres que contengan search
}

I had this code to do a search in my DB where I have name and surname. I want this query to be valid for all those instances in which the name contains the search string, but I would also like to add the search by last name, since if something other than the name appeared in search, the query would be executed incorrectly. How could I implement such a query to be able to filter by first and last name?

2

Answers


  1. you can use regex

    query := bson.M{
            "nombre": bson.M{"$regex": `s`+surname+`b`},
        }
    
    

    s matches any whitespace character

    b assert ending

    Login or Signup to reply.
  2. Since we don’t know if user will pass only first name or first name with last name

    search := "Carlos M"
    s := strings.Split(search, " ")
    s := append(s, "") // incase name is only supplied then empty string will be used for surname
    query := bson.M{
        "nombre": bson.M{"$regex": `(?i)` + s[0]},
        "apellido": bson.M{"$regex": `(?i)` + s[1]},
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search