使用 Golang mgo 进行用户搜索

User search with Golang mgo

获取字符串作为输入(来自用户搜索),我正在尝试为 mgo 构建一个 bson.M 对象以搜索 mongo 数据库并找到 x 个项目。

像这样

func Search (w http.ResponseWriter, r *http.Request) {

    q := r.FormValue("q")
    filter := bson.M{}
    // magic happens here 

    // do db connection stuff
    things := []*thing{}
    err := db.Find(&filter).Limit(10).All(&things)
    // check error, send things, etc
}

我需要搜索依据的是

例如,如果存储的数据看起来像 {title: "abcde"},那么

编辑:解决方案

我终于想通了。神奇的部分是这样的:

q := r.FormValue("q")
qs := strings.Split(q, " ")
and := make([]bson.M, len(qs))
for i, q := range qs {
    and[i] = bson.M{"title": bson.M{
        "$regex": bson.RegEx{Pattern: ".*" + q + ".*", Options: "i"},
    }}
}
filter := bson.M{"$and": and}

mongo过滤器可以采用正则表达式,例如;

        bson.M{"title": bson.M{"$regex": bson.RegEx{Pattern: title, Options: "i"}}}

所以在这种情况下,标题变量应该是这样的; .*abc*.。选项:"i" 启用不区分大小写。

至于匹配子字符串(场景2)我不知道如何在正则表达式中实现。

简单使用这个,

wordOffset := q

selector:= bson.M{"title": bson.M{"$regex": wordOffset}}