1

Here is the setup.

user has_many skills
skills belongs_to user

I would have to find out all users that have skills with ids 1,2 and 3

I can use intersection of three user collections.

Skill.find(1).users & Skill.find(2).users & Skill.find(3).users  

But this does not seem efficient. Is there a query in Mongoid/MongoDB that resembles the following?

User.where(:skill_ids.contains=>[1,2,3])

PS: I know Mongoid gives the in keyword:

User.where(:skill_id.in=>[1,2,3])
benzhang
  • 471
  • 4
  • 11

1 Answers1

3

I think you're looking for MongoDB's $all query operator:

$all

The $all operator is similar to $in, but instead of matching any value in the specified array all values in the array must be matched.
[...]
An array can have more elements than those specified by the $all criteria. $all specifies a minimum set of elements that must be matched.

Mongoid provides access to $all through all_in which I think is available as .all on symbols so I think this:

User.where(:skill_id.all => [1,2,3])

should work for you.

mu is too short
  • 426,620
  • 70
  • 833
  • 800