1

In a mongo database with an array field titled interests, when i need to look for people interested in either judo OR mma, i write the query like this:

{interests : {$regex: "judo|mma", $options: 'i'}}

How do i find people interested in judo AND mma?

Note: I've tried the following and various variations of these but none seem to work :

{interests : {$regex: "(?=judo)(?=mma)", $options: 'i'}},
{interests : {$regex: "(?=.*judo)(?=.*mma)", $options: 'i'}}

Thanks.

  • Currently, you're trying to check if a string is both at the same time "judo" and "mma". This of course is never happening. Can you provide an example on how your data is structured in this case ? – Pac0 Jan 21 '20 at 12:28
  • `(?=.*judo)(?=.*mma)` should work. – Wiktor Stribiżew Jan 21 '20 at 12:29
  • @Pac0 sure! inrerests is an array of this structure: ``` interests : { type: Array, default: [] } ``` – gratefulching4 Jan 21 '20 at 15:10
  • can you try something like : `{interests: {$all: [/^judo/, /^mma/], , $options: 'i'}}` – Pac0 Jan 21 '20 at 15:21
  • @WiktorStribiżew it's an array , that contain maybe elements like either "judo", "mma", or "other", or none of them. It's not one comma separated string where you perform one search. like in "judo, other, mma" – Pac0 Jan 21 '20 at 15:25
  • @Pac0 thank you so much it works! but to use options, i need to use regex otherwise it's giving me an error. any workaround to do a case insenstive search? – gratefulching4 Jan 21 '20 at 15:47
  • can you try adding the 'i' just after each regex like this instead :$all: [/^judo/i, /^mma/i – Pac0 Jan 21 '20 at 16:27
  • (like here : https://stackoverflow.com/questions/1863399/mongodb-is-it-possible-to-make-a-case-insensitive-query) – Pac0 Jan 21 '20 at 16:28

1 Answers1

2

something like this should work :

{interests: {$all: [/^judo$/i, /^mma$/i]}
Pac0
  • 21,465
  • 8
  • 65
  • 74
  • is there anyway to do this case insensitive search if the array is being sent directly to the function? eg. array: `["judo","mma"]` – gratefulching4 Apr 03 '20 at 07:27
  • You can dynamically map each string of the array to a regexp by using `map` and `new RegExp` : `["judo","mma"].map(x => new RegExp(x, "i"))` (I'll let you add the anchors `^` and `$` around the string `x` if you want). The output will be an array of regexps, so it should work (not tested, no mongodb near me) – Pac0 Apr 03 '20 at 07:43