Maor Barazani
Maor Barazani

Reputation: 840

MongoDB: Match multiple values in string field

I have a collection of entities that contain a string field. I'm looking for a way to query the collection with a combined number of values, and get all entities that contain all of these values, with these specifications:

  1. contain ALL provided query values, not just some of them
  2. case-insensitive
  3. regardless of order
  4. 'word' query values can be part of something bigger (for example separated by _ or any other character)

So as an example, if I provide these words as the query values:
i am spiderman (I can separate them by whitespace, give an array, or whatever works..)

I expect these results:

 - "i am_spiderMan"                     // should match
 - "AM i spiderman?!"                   // should match
 - "who am I? supermanspiderman"        // should match
 - "I am superman"                      // should not match
 - "i am spider_man"                    // should not match

I hope this covers all the cases I tried to describe. I tried regex, and also did some research with similar questions but could not get it to work.

Upvotes: 1

Views: 2295

Answers (1)

varman
varman

Reputation: 8894

You could use regular expr. This is working perfectly. When you pass the sentence, you need to put all worlds into array as I have shown below. Refer $all to include all words to find. Reg expr case insensitive

db.collection.find ({ key: { $all: [ /spiderman/i, /i/i, /am/i ] } })

Upvotes: 3

Related Questions