I have a model like this
class User
include Mongoid::Document
field :c, as: :categories, type: Array
end
and I am storing information on it like this:
a = UserCheckin.new
a.c = [{id: rand(1000), name: 'a'}, {id: rand(1000), name: 'b'}, {id: rand(1000), name: 'c'}]
a.save
I do not know if I am misusing the array type by storing hashes on it, but the thing is that mongodb does not complain about it.
How do I query something like Users where category name is 'a' or category id is higher than 2?
Thanks in advance,
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>, ... } }
The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. If you specify only a single <query> condition in the $elemMatch expression, and are not using the $not or $ne operators inside of $elemMatch , $elemMatch can be omitted.
To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
Use the $in Operator to Match Values This query selects all documents in the inventory collection where the value of the quantity field is either 5 or 15. Although you can write this query using the $or operator, use the $in operator rather than the $or operator when performing equality checks on the same field.
I've seem to have find the answer... For anyone left, I will post it here.
User.where(c: {'$elemMatch' => {name: 'a'}})
It will return all the Users, whose categories array has one or more element with a name of 'a'.
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