英文:
User search with Golang mgo
问题
获取一个字符串作为输入(来自用户搜索),我正在尝试构建一个bson.M
对象,用于mgo
在Mongo数据库中搜索并找到x个项目。
类似这样的代码:
func Search(w http.ResponseWriter, r *http.Request) {
q := r.FormValue("q")
filter := bson.M{}
// 在这里进行一些操作
// 进行数据库连接
things := []*thing{}
err := db.Find(&filter).Limit(10).All(&things)
// 检查错误,发送things等等
}
我需要搜索基于以下条件:
- 忽略大小写(我找到了这个答案,它帮助了我一部分)
- 存储的数据中的
title
必须在某个地方包含q
中的每个单词。
所以,例如,如果存储的数据看起来像{title: "abcde"}
,那么
Abc
会匹配de Bc
会匹配ac
不会匹配
编辑:解决方案
我最终找到了解决方法。魔法部分如下:
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}
以上是翻译好的内容,请确认是否满意。
英文:
Getting a string as input (from a user search), I am trying to construct a bson.M
object for mgo
to search through the mongo database and find x number of items.
Something like this
<!-- language: lang-golang -->
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
}
What I need the search to be based on is
- ignore case (I found this answer which takes me part of the way)
- the
title
in the stored data must, somewhere, include each of the words in theq
.
So for instance if the stored data looks like {title: "abcde"}
, then
Abc
will matchde Bc
will matchac
will not match
Edit: Solution
I finally figured it out. The magic part looks like this:
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}
答案1
得分: 1
mongo过滤器可以使用正则表达式,例如:
bson.M{"title": bson.M{"$regex": bson.RegEx{Pattern: title, Options: "i"}}}
所以在这种情况下,title变量可能是类似于.*abc*.
的内容。Options: "i"表示不区分大小写。
至于匹配子字符串(场景2),我不确定如何在正则表达式中实现。
英文:
The mongo filter can take regex, for example;
bson.M{"title": bson.M{"$regex": bson.RegEx{Pattern: title, Options: "i"}}}
So in this case the title variable would be something like; .*abc*.
. The Options: "i" enables case insensitivity.
As for matching the substring (scenario 2) I am not sure how to achieve within regex.
答案2
得分: 0
简单使用如下:
wordOffset := q
selector := bson.M{"title": bson.M{"$regex": wordOffset}}
英文:
Simple use this,
wordOffset := q
selector:= bson.M{"title": bson.M{"$regex": wordOffset}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论