Mongodb-如何在多个字段中查找字符串? [英] Mongodb - How to find string in multiple fields?

查看:77
本文介绍了Mongodb-如何在多个字段中查找字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下使用Pymongo.

Using Pymongo for this scenario.

我有一个拥有电子邮件,名字,姓氏的用户.

I have User that has email, first_name, last_name.

我正在使用以下Pymongo代码段:

I am using this Pymongo snippet:

user_found = users.find({'$or':[
            {'email':{'$regex':searchString, '$options':'i'}},
            {'first_name':{'$regex':searchString, '$options':'i'}},
            {'last_name':{'$regex':searchString, '$options':'i'}}]})

如果我想在以下位置找到searchString,则此示例有效:

this example works, if I want to find searchString in:

  • 电子邮件,或
  • 名字或
  • 姓氏

现在,我还需要在"first_name + last_name"组合中找到searchString.

now I need to also find searchString in first_name + last_name combined.

我该怎么做? 在mongo中,有没有一种方法可以通过查询将两者组合成一个全名",然后搜索全名?

how can I do that? Is there a way in mongo, through the query, to combine the two into a "fullname" then search the fullname?

推荐答案

最简单的方法是添加一个数组字段,并使用要搜索的所有变体填充它.对该数组字段进行索引.

Easiest way is to add an array field and populate it with all of the variants that you want to search on. Index that array field.

这样,您只需要一个索引,并且在所有字段中进行的搜索都非常简单,并且当您要搜索某些新的搜索变体时不会改变.您还可以规范化放入搜索数组中的文本,例如,将其下划线,删除标点符号等.

That way you only need one index and your search across all fields is simple and doesn't change when you want to search on some new search variant. You can also normalize the text you put into the search array, for example, lower casing it, removing punctuation etc.

请参见 https://stackoverflow.com/q/8206188/224370

编辑:现在,MongoDB的文档涵盖了全文搜索功能.

MongoDB's documentation now covers keyword search and the new full-text search feature.

这篇关于Mongodb-如何在多个字段中查找字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆