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?
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>, ... } }
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.
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.
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.
In mongoid, there is '$in' operator. So you can do this :
Model.where(category: { '$in': ['val1', 'val2'] })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With