在 MongoDB 查询中搜索 2 个属性
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为我们不知道用户是否只传递名字或名字和姓氏
Since we don't know if user will pass only first name or first name with last name
您可以使用正则表达式
\s 匹配任何空白字符
\b 断言结束
you can use regex
\s matches any whitespace character
\b assert ending