Search code examples
mongodbgomgo

How to find the data from collection according to url in golang?


I'm retrieving the data from the database when the user hit the url like http://localhost:8080/api/v1/customer?keyword=dhiman then it search for the data in the collection if there is any field matches then it will retrieve that data. if the user entered the short url like http://localhost:8080/api/v1/customer?keyword=dhi then it also retrieve the data which matches like that how I'll solve this problem. I tried the code for this like following:-

Struct of the customer

type Customer struct {
  Id               int    `json:"id" bson:"_id"`
  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"`
}
type Customers []Customer

Functions

func GetCustomers(c *gin.Context) {
value := c.Query("keyword")
fmt.Println(value)
response := ResponseControllerList{}
conditions := bson.M{"last_name":value}
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,
        // dataCount,
        nil,
    }
}
GetResponseList(c, response)
} 

GetCustomerListing function in models page:-

func GetCustomerListing(customerQuery interface{}) (result Customers, err error) {
mongoSession := config.ConnectDb()
sessionCopy := mongoSession.Copy()
defer sessionCopy.Close()
getCollection := mongoSession.DB(config.Database).C(config.CustomerCollection)
err = getCollection.Find(customerQuery).Select(bson.M{"password": 0}).All(&result) //.Skip(skip).Limit(limit)
if err != nil {
    return result, err
}
return result, nil
}

collection images


Solution

  • I got the answer it is done by using the $or in mongodb.

    In the monogdb there is a operator called or $or it checks the value with all the fields and produce result.

    There is a bson.RegExis used. Because it will matches or checks the data similar to it receives from the user.

    There is change in condition. The condition is:-

    conditions := bson.M{"$or": []bson.M{
        bson.M{"first_name": bson.RegEx{value,""}},
        bson.M{"last_name": bson.RegEx{value,""}},
        bson.M{"email": bson.RegEx{value,""}},
        bson.M{"phone_number": bson.RegEx{value,""}},
    }}
    

    there is change in the query