Let us say you have the following models:
class User
embeds_many :book_marks, :validate => false, :cascade_callbacks => true
end
class BookMark
field :url, type: string
field :category, type: string # personal, work
field :tags, type: Array
embedded_in :user
end
Let us say we wount to count the number of users with book marks in personal category with technology tags.
User.where(:"book_marks.category" => "personal",
:"book_marks.tags".in => ["technology"]).count
For the data set below, the query will return both rows.
name book_marks
category tags
============ ======== ====
Tom personal politics
work technology
Jack personal finance
personal technology
We have to modify the query so that we multiple attributes of a single embedded document. MongoDB provides a construct
called elem_match for such requirements.
User.where(:book_marks.elem_match =>
{ :category => "personal", :tags.in => ["technology"]).count
Now the query will only match Jack.