newBike
newBike

Reputation: 15002

How could I query by one of multiple possible value in mongoid

from = [:TPE, :TOKYO, :CHICHAGO]

where(
  from: /.*#{from}.*/i,
)

Input documents

{
    from: 'PARIS'
},
{
    from: 'PARIS'
},
{
    from: 'TOKYO'
},
{
    from: 'TPE'
}    

Output documents

{
    from: 'TOKYO'
},
{
    from: 'TPE'
}    

Upvotes: 1

Views: 691

Answers (1)

mu is too short
mu is too short

Reputation: 434685

You can use an $in operator to see if a field matches anything in an array:

where(:from => { :$in => array })

Mongoid patches the MongoDB operators into Symbol as methods so you could also say:

where(:from.in => array)

If you really are looking for values that contain any of the values in an array then you could just build a single regex that does that using alternation:

re = /#{array.map { |s| Regexp.escape(s.to_s) }.join('|')}/i
Model.where(:from => re)

Note that there's no leading or trailing .* in the regex as that doesn't do anything useful. Also note the presence of Regexp.escape calls before the components are joined with the regex alternation operator (|).

Upvotes: 1

Related Questions