Querying an array field containing hashes in mangoids

I have a model like this

class User
  include Mongoid::Document
  field :c, as: :categories, type: Array
end

and I store the information on it as follows:

a = UserCheckin.new
a.c = [{id: rand(1000), name: 'a'}, {id: rand(1000), name: 'b'}, {id: rand(1000), name: 'c'}]
a.save

I don’t know if I am abusing array type by storing hashes on it, but the fact is that mongodb does not complain about it.

How can I request something like Users where the category name is "a" or the category identifier is above 2?

Thanks in advance,

+5
source share
1 answer

I think I found the answer ... For someone, I will post it here.

User.where(c: {'$elemMatch' => {name: 'a'}})

It will return all Users whose array of categories has one or more elements named "a".

+12
source

All Articles