Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb - How to find string in multiple fields?

Tags:

Using Pymongo for this scenario.

I have User that has email, first_name, last_name.

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'}}]})

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

  • email, or
  • first_name, or
  • last_name

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

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?

like image 771
Bach Avatar asked Nov 23 '11 06:11

Bach


People also ask

How do I search multiple values in MongoDB?

MongoDB provides the find() that is used to find multiple values or documents from the collection. The find() method returns a cursor of the result set and prints all the documents. To find the multiple values, we can use the aggregation operations that are provided by MongoDB itself.

How do I search for a string in MongoDB?

Use the $text query operator to perform text searches on a collection with a text index. $text will tokenize the search string using whitespace and most punctuation as delimiters, and perform a logical OR of all such tokens in the search string.

How do I search for fields in MongoDB?

to do a text search on all fields, you first must create a text index on all fields. as the mongodb documentation indicates, "To allow for text search on all fields with string content, use the wildcard specifier ($**) to index all fields that contain string content."

What is $Not in MongoDB?

$not performs a logical NOT operation on the specified <operator-expression> and selects the documents that do not match the <operator-expression> . This includes documents that do not contain the field .


1 Answers

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.

See https://stackoverflow.com/q/8206188/224370

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

like image 90
Ian Mercer Avatar answered Sep 22 '22 17:09

Ian Mercer