3

I have a Map object with a 'cities' array field

class Map
  include Mongoid::Document
  field :cities, type: Array
end

I want to search for all the Map where at least one city is present from an other array. Something like this:

# map1.cities = ['London', 'Manchester']
# map2.cities = ['Paris', 'Lyon']
# map3.cities = ['Berlin', 'Munich']
# searchedCities = ['London', 'Paris']

I want all the maps that contains at least one of the searchedCities, in this case; map1 and map2.

This is not working, because it compares the whole array

Map.where(cities: searchedCities)

any ideas ?

3
  • Try Map.any_in(cities: searched_cities) Commented Aug 2, 2018 at 17:27
  • 1
    That's works great. Thanks a lot. I've probably missed that query in the documentation. Commented Aug 3, 2018 at 6:41
  • I will add it as an answer for future visitors. Commented Aug 3, 2018 at 6:46

1 Answer 1

2

You can use .any_in (can't find a direct documentation) which generates a $in mongodb query for you and it matches the document if the field contains any of the values from given array.

In your case:

Map.any_in(cities: searched_cities)
 => #<Mongoid::Criteria
  selector: {"cities"=>{"$in"=>["London", "Paris"]}}
  ...
  class:    Map>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.