chopi321
chopi321

Reputation: 1411

Querying an array field that contains hashes in mongoid

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,

Upvotes: 5

Views: 2415

Answers (1)

chopi321
chopi321

Reputation: 1411

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'.

Upvotes: 12

Related Questions