在 MongoDB 查询中搜索 2 个属性

发布于 2025-01-15 12:20:31 字数 308 浏览 0 评论 0原文

query := bson.M{
    "nombre": bson.M{"$regex": `(?i)` + search}, // me va a buscar los nombres que contengan 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

您的好友蓝忘机已上羡 2025-01-22 12:20:31

因为我们不知道用户是否只传递名字或名字和姓氏

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

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]},
}
寻找我们的幸福 2025-01-22 12:20:31

您可以使用正则表达式

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文