Search code examples
ruby-on-railsarraysmongodbruby-on-rails-4mongoid

How to check if an Mongoid array field contains one or more items in another array?


If the field is an integer, then the following works:

User.where(id: [1,3,5])    

But what if the field is an array? For example, the user has a field which is an array of favorite_numbers:

How to find users that have a favorite_number of 1, 3 or 5?

Rails 4.1.7
Mongoid 5.0.0

Edit: Added Mongoid.


Solution

  • I'm not certain about Mongoid 5 but the $in operator should take care of unrolling the right side:

    User.where(:favorite_numbers.in => [1,3,5])
    # or
    User.where(favorite_numbers: { :$in => [1,3,5] })
    User.where(favorite_numbers: { '$in' => [1,3,5] })
    User.where(favorite_numbers: { '$in': [1,3,5] }) # depending on Ruby version
    

    MongoDB itself will take care of unrolling the favorite_numbers array.