19

I have a category field of type Array in Mongoid.

Ex. category: ["val1","val2","val3"]

Now I want to query this Model with `category: ["val1","val2"] such that it returns me the merge of

Model.where(category: "val1") and Model.where(category: "val2")

I can do it individually for each element of the array but that will be slow I guess because for every individual element it will search all the documents.

I also tried Model.all_of({category: "val1"},{category: "val2"}).all but that is not working.

How should I do this?

mrudult
  • 2,480
  • 3
  • 35
  • 54
  • 1
    Third read is, hopefully, a more accurate one. Try: Model.select{|m|m.category.include?("val1") || m.category.include?("val2")} (provided the category field is never a nil value). – Tebc Nov 08 '13 at 20:47
  • the first one was more robust and easy – mrudult Nov 08 '13 at 20:56

4 Answers4

36

In mongoid, there is '$in' operator. So you can do this :

Model.where(category: { '$in': ['val1', 'val2'] })
kd12
  • 1,291
  • 1
  • 13
  • 22
  • 3
    This gives me a syntax error. I had to use: Model.where(category: { '$in' => ['val1', 'val2'] }) Note the use of '=>' instead of ':' – Ahmed Fathy Aug 08 '14 at 13:41
  • 9
    @AhmedFathy: Or just say `Model.where(:category.in => ['val1', 'val2'])`. Mongoid adds similar methods to Symbol for the other MongoDB operators: `:f.ne => ...`, `:f.gt => ...`, ... – mu is too short Oct 29 '14 at 17:40
12

You can use Criteria all_in to make it simpler:

Model.all_in(category: ['val1','val2'])
borjagvo
  • 1,802
  • 2
  • 20
  • 35
8

This worked

Model.where(:category.in => ['val1','val2'])

From Mongo Docs

Maged Makled
  • 1,918
  • 22
  • 25
2

Or another variant:

Model.in(category: ['val1','val2'])
Jon Kern
  • 3,186
  • 32
  • 34