简体   繁体   中英

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,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM