英文:
Search on 2 properties in MongoDB query
问题
query := bson.M{
"$or": []bson.M{
bson.M{"nombre": bson.M{"$regex": `(?i)` + search}},
bson.M{"apellido": bson.M{"$regex": `(?i)` + search}},
},
}
我有这段代码用于在我的数据库中进行搜索,其中包含姓名和姓氏。我希望这个查询对于所有包含搜索字符串的姓名实例都有效,但我也希望能够通过姓氏进行搜索,因为如果搜索中出现了除姓名以外的内容,查询将执行不正确。如何实现这样的查询以能够通过名字和姓氏进行过滤呢?
英文:
query := bson.M{
"nombre": bson.M{"$regex": `(?i)` + search}, // me va a buscar los nombres que contengan search
}
I had this code to do a search in my DB where I have name and surname. I want this query to be valid for all those instances in which the name contains the search string, but I would also like to add the search by last name, since if something other than the name appeared in search, the query would be executed incorrectly. How could I implement such a query to be able to filter by first and last name?
答案1
得分: 1
由于我们不知道用户是否只会提供名字或名字和姓氏,因此需要进行以下翻译:
search := "Carlos M"
s := strings.Split(search, " ")
s := append(s, "") // 如果只提供了名字,则使用空字符串作为姓氏
query := bson.M{
"nombre": bson.M{"$regex": `(?i)` + s[0]},
"apellido": bson.M{"$regex": `(?i)` + s[1]},
}
英文:
Since we don't know if user will pass only first name or first name with last name
search := "Carlos M"
s := strings.Split(search, " ")
s := append(s, "") // incase name is only supplied then empty string will be used for surname
query := bson.M{
"nombre": bson.M{"$regex": `(?i)` + s[0]},
"apellido": bson.M{"$regex": `(?i)` + s[1]},
}
答案2
得分: 0
你可以使用正则表达式
query := bson.M{
"nombre": bson.M{"$regex": `\s`+surname+`\b`},
}
\s 匹配任何空白字符
\b 断言结尾
英文:
you can use regex
query := bson.M{
"nombre": bson.M{"$regex": `\s`+surname+`\b`},
}
\s matches any whitespace character
\b assert ending
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论