0

Hi guys this is my first question!

I'm learning MongoDB and I wanted to ask you about the difference between the following three approaches to filter documents within a collection:

Reg. Exp.

Plant
  .find( { effects: /.*(hallucinogenic|sedating).*/ } )

comparison operator in

Plant
  .find( { effects: { $in: [ 'hallucinogenic', 'sedating' ] } } )

logical operator OR

Plant
  .find()
  .or( [ { effects: 'hallucinogenic' }, { effects: 'sedating' } ] )

Are these approaches just personal preference choice or are they different in some term?

My personal preference is to use a Regular Expression, is there any drawback to that approach?

Fredo Corleone
  • 544
  • 1
  • 6
  • 16
  • Kind of broad except that the "regex" here is not equal to the other expressions. For the regex to be doing the same thing it needs to be "start anchored" and "end anchored" to contain exactly and **only** that word. Otherwise it's comparing "apples" to "meat pies". Two completely different things. – Neil Lunn May 18 '18 at 08:54
  • The short is of course use `$in` where you can, since MongoDB can optimize more for this with foreknowledge that it applies to the same field, and without the regex compilation. ( when the regex is the same thing of course - example in linked answer ) – Neil Lunn May 18 '18 at 09:02

0 Answers0