Mongoid Query for Array Field

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?

2

4 Answers

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

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

You can use Criteria all_in to make it simpler:

Model.all_in(category: ['val1','val2'])

This worked

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

From Mongo Docs

Or another variant:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest