【问题标题】:How to find the data from collection according to url in golang?如何根据golang中的url从集合中找到数据?
【发布时间】:2018-09-12 17:59:24
【问题描述】:

当用户点击http://localhost:8080/api/v1/customer?keyword=dhiman 之类的网址时,我正在从数据库中检索数据,然后如果有任何字段匹配,它将在集合中搜索数据,然后它将检索该数据。如果用户输入像http://localhost:8080/api/v1/customer?keyword=dhi 这样的短网址,那么它也会检索匹配的数据,我将如何解决这个问题。我尝试了如下代码:-

客户结构

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

功能

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函数:-

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
}

收藏图片

【问题讨论】:

  • 您遇到了什么问题/错误? Customers 类型的定义是什么?
  • @icza 我编辑我的问题
  • 它在用户输入姓氏时检索数据,但如果它输入名字,那么它不会检索我想要的数据如果用户输入任何字段数据,那么它会检索与它匹配的数据例如http://localhost:8080/api/v1/customer?keyword=puneet 然后它与集合first_name 匹配并检索它@icza
  • 这个问题看起来可以这样写:“在 mongodb 中我如何查询、多个字段和/或执行 SQL LIKE 过滤器”。如果这是问题,只需查询 SO 就会得到答案。问题的 URL 和网络似乎不相关。

标签: mongodb go mgo


【解决方案1】:

我得到了答案,它是通过在 mongodb 中使用 $or 完成的。

在monogdb中有一个称为或$or的运算符,它检查所有字段的值并产生结果。

使用了bson.RegExis。因为它会匹配或检查类似于它从用户那里收到的数据。

情况有变化。条件是:-

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,""}},
}}

查询有变化

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 2019-12-11
    • 2022-10-13
    • 2016-07-21
    • 1970-01-01
    相关资源
    最近更新 更多