ruby-on-railsmongoidmongodb-querymoped

mongoid: select elements that have at least n elements in array


In mongoid you can query items that have at least one element in array:

Item.any_in(tag_ids: [id1,id2,id3])

You can also select elements that have all elements in array:

Item.all_in(tag_ids: [id1,id2,id3])

My Question: Is there any way to query elements that have at least n elements in array ?

I'd like to query something like Item.at_least(tag_ids: [id1,id2,id3], n: 2) to return any Item that share at least two ids with [id1,id2,id3]

Thanks !


Solution

  • I don't know a pure Mongoid-solution. I also haven't found such query in the MongoDB manual: http://docs.mongodb.org/manual/reference/operator/query-array/

    I would use some mix of Mongoid and array operations. The disadvantage of it is, that all items which have at least 1 of these tags will be loaded.

    searched_tag_ids = ['54253ad452656b1d25000000','54253adc52656b1d25010000','54253ae352656b1d25020000']
    items_with_min_1_searched_tag = Item.any_in(tag_ids: searched_tag_ids).to_a
    items_with_min_2_searched_tag = items_with_min_1_searched_tag.select{|item| (item.tag_ids.collect{|tag_id| tag_id.to_s} & searched_tag_ids).size >=2}