I have got two classes
class Claim
include Mongoid::Document
embeds_many :claim_fields
belongs_to :user
...
end
class ClaimField
include Mongoid::Document
embedded_in :claim
field :title
field :value
...
end
I need to fetch all unique values for claim_fields with current title for my claim through db (not by Ruby – it is too slow for thousands of records)
I’ve already tryied this
user = User.find(...)
Claim.collection.distinct("claim_fields.value", {:user_id => user.id, "claim_fields.title" => some_title})
# that is the same as user.claims.find(...).distinct("claim_fields.value")
But it returns ALL claim_fields values, and I need it to return only values for claim_fields with title that I need.
PS looks that I need some MapReduce here
The fundamental problem here is that MongoDB queries only return entire documents. You are filtering on
claim_fields.title, but the system is returning allClaimdocuments that match.You’re doing a
distinct, but MongoDB treats sub-objects and Documents differently. As a result, thedistinctis probably not doing what you want it to.There are two possible solutions here:
Regarding #2, there is no requirement for embedding objects as you have. Embedded should be done based on the queries you plan to perform most. So if this is a common query, then it’s fair to make these separate documents.