Mongoid query for array field

mrudult picture mrudult · Nov 8, 2013 · Viewed 13.9k times · Source

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?

Answer

kd12 picture kd12 · Nov 8, 2013

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

Model.where(category: { '$in': ['val1', 'val2'] })