user2483718
user2483718

Reputation: 11

Using Mongoid to do counts of embedded objects

I have 2 collections, Article, Author. An article can have 0 to N number of Authors. An article can be one of many article_types ( article_type is a String ).

Article ... field :article_type :type => String ... has and belongs to many :authors ...

Author field :author_name :type => String ....

What is the best way to use Mongoid to get the number of articles that each author belongs to for a specific article type. For example, the output should be a hash:

'John Smith' : 2 'Mary Jones' : 10 'Tom Petty' : 22

Thanks!

Upvotes: 1

Views: 1055

Answers (2)

Gary Murakami
Gary Murakami

Reputation: 3402

The Aggregation Framework is recommended as it can be 5-10 times faster than map/reduce. The MongoDB documention is at http://docs.mongodb.org/manual/core/aggregation/ but to access it from Mongoid, you have to dip down to the Moped level using Article.collection.aggregate or Author.collection.aggregate. Reference Aggregate with Mongoid

Upvotes: 1

Ismael
Ismael

Reputation: 16730

You might need to use map reduce http://mongoid.org/en/mongoid/docs/querying.html#map_reduce

Upvotes: 1

Related Questions