Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 507
mrudult Avatar asked Nov 08 '13 20:11

mrudult


People also ask

How do I query an array field in MongoDB?

To query if the array field contains at least one element with the specified value, use the filter { <field>: <value> } where <value> is the element value. To specify conditions on the elements in the array field, use query operators in the query filter document: { <array field>: { <operator1>: <value1>, ... } }

How do I match an array element in MongoDB?

MongoDB query to match documents with array values greater than a specific value. You can use $elemMatch. The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

How do I create an array field in MongoDB?

Case 1 − Create array with MongoDB. If you want to create an array of field UserName and do not want the field _id, use the below query. If you want to create an array with field name _id only, use the below query.

How do I query a nested field in MongoDB?

Query on Nested Field To specify a query condition on fields in an embedded/nested document, use dot notation ( "field. nestedField" ). When querying using dot notation, the field and nested field must be inside quotation marks.


1 Answers

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

Model.where(category: { '$in': ['val1', 'val2'] })
like image 112
kd12 Avatar answered Sep 30 '22 07:09

kd12