Reputation: 4492
what is the most efficient way to return all embedded documents?
say a User has many Addresses embedded... in ActiveRecord i could get a count of them with Address.count. what is the embedded document / mongo version of doing this?
how about when its 2 or more levels deep? Product > Pressing > Variations... how could i get a count of all the chapters across all books, across all authors? how would it compare to doing it all in say, Ruby?
Product has_many Pressings
Pressing has_many Variations
Product
def self.pressings
all.collect { |p| p.pressings }.flatten
end
def self.variations
self.pressings.collect { |p| p.variations }.flatten
end
end
Upvotes: 2
Views: 1315
Reputation: 9210
As @maga says, Map/Reduce is too slow for realtime aggregation and storing a counts field is the best way.
Another option is to return the entire document (or specific fields) to your application and have it be parsed there. This may be best when you dont know how many nested levels are going to exist.
Despite what some people may think, there is absolutely no harm in doing this. Your database server will gladly return this document very quickly and allow your application to handle the post processing.
In terms of scalability, this approach means you'll be scaling your application servers (which are usually much more affordable) instead of your database servers (which are typically more expensive).
Upvotes: 4
Reputation: 720
Usually it's done by aggregation functions (including map/reduce for more specific situations) but they are relatively slow and not appropriate for real-time using in heavy applications. So, If performance is issue, I suggest additional number fields, updated by atomic operations when changes occur and amended by aggregation functions from time to time.
Upvotes: 5
Reputation: 9973
Map/reduce in MongoDB is useful for batch processing of data and aggregation operations.
Upvotes: 2