benzhang
benzhang

Reputation: 471

How to query all records that has an array attribute that contains specific set of elements in Mongoid?

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])

Upvotes: 1

Views: 309

Answers (1)

mu is too short
mu is too short

Reputation: 434685

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.

Upvotes: 3

Related Questions