Search code examples
mongodbgomgo

how to get the data according to the data entered in the query string in golang?


I'm retrieving the data from the collection in mongodb matches to the data enter in the query string using golang.

There are two cases

case 1

Suppose if user search the single field like first_name, last_name etc. Then the data will be retrieve by hitting the url http://localhost:8080/api/v1/customer?keyword=puneet

case 2

In case 2 suppose we have the two fields in collection of mongodb for example first_name : puneet, last_name : jindal,etc. If the user will enter the two fields in the query string first_name and last_name

Example hitting the url like http://localhost:8080/api/v1/customer?keyword=puneet%20kumar then there is no data retrieval.

I have tried the following code for this. But not success

Struct for this is:

type Customer struct {
  Id          int    `json:"id" bson:"_id"`
  Name        string `json:"name" bson:"name"`
  FirstName   string `json:"first_name" bson:"first_name"`
  LastName    string `json:"last_name" bson:"last_name"`
  Email       string `json:"email" bson:"email"`
  PhoneNumber string `json:"phone_number" bson:"phone_number"`
}

Function for retrieving the data:

func GetCustomers(c *gin.Context) {
value:= c.Query("keyword")
fmt.Println(value)
response := ResponseControllerList{}
conditions := bson.M{"$or": []bson.M{
    bson.M{"first_name": bson.RegEx{".*" + value, "i"}},
    bson.M{"last_name": bson.RegEx{".*" + value, "i"}},
    bson.M{"email": bson.RegEx{".*" + value, "i"}},
    bson.M{"phone_number": bson.RegEx{".*" + value, "i"}},
}}
data, err := models.GetCustomerListing(conditions)
if err != nil {
    response = ResponseControllerList{
        config.FailureCode,
        config.FailureFlag,
        config.FailureMsg,
        nil,
        nil,
    }
} else {
    response = ResponseControllerList{
        config.SuccessFlag,
        config.SuccessFlag,
        config.SuccessMsg,
        data,
        nil,
    }
}
GetResponseList(c, response)
}

Solution

  • I made the solution

    value:= c.Query("keyword")
    fmt.Println(value)
    response := ResponseControllerList{}
    name := strings.Replace(value, " ", "|", -1)
    conditions := bson.M{"$or": []bson.M{
        bson.M{"first_name":bson.RegEx{"(?i).*"+name+".*", "i"} },
        bson.M{"last_name": bson.RegEx{ "(?i).*"+name+".*", "i"} },
        bson.M{"email": bson.RegEx{".*" + value, "i"}},
        bson.M{"phone_number": bson.RegEx{".*" + value, "i"}},
    }}
    

    change in the query