count hasMany relation in mongodb/mongoid -
enter code herei"m working on rails app running mongodb via mongoid. let's have 2 collections , posts , comments, , they're linked habtm relation, i'd select posts have comments, , think way count comments each post , order comments.count desc. don't know how count number of comments each posts, add column posts results count(comments) comments_count
in sql, , order "pseudo-field".
any thoughts on ?
thanks
edit, looking @ others answers related this, i've tried:
db.posts.aggregate([ { $group: { _id: { post_id: '$post_id', comment_id: '$comment_id' } }}, { $group: { _id: '$_id.post_id', comments_count: { $sum: 1 } }}] , function(err, result){ console.log(result); } );
i'm getting
{ "result" : [{ "_id" : null, "datasets_count" : 1 }], "ok" : 1 }
the aggregation framework in mongodb has operators grouping, summing, , sorting. following working example of how group, count, , sort posts number of comments. hope want , helps.
models/post.rb
class post include mongoid::document has_many :comments field :text, type: string end
models/comment.rb
class comment include mongoid::document belongs_to :post field :text, type: string end
test/unit/post_test.rb
require 'test_helper' require 'pp' class posttest < activesupport::testcase def setup post.delete_all comment.delete_all end test "posts ordered comment count" [ [ "now time men come aid of country.", [ "tally ho!" ] ], [ "twas brillig, , slithy toves did gyre , gimble in wabe.", [ "off heads!", "the time has come, walrus said.", "curiouser , curiouser." ] ], [ "the quick brown fox jumped on lazy dog.", [ "the typewriter mightier sword.", "dachshund badger dog." ] ] ].each |post, comments| post = post.create(text: post) comments.each{|comment| post.comments << comment.create(text: comment)} end pipeline = [ { '$group' => { '_id' => '$post_id', 'count' => { '$sum' => 1 } } }, { '$sort' => { 'count' => -1} } ] result = comment.collection.aggregate(pipeline).to_a.collect |post_id_count| post.find(post_id_count['_id']) end puts pp result end end
rake test
running tests:
[1/1] posttest#test_posts_ordered_by_comment_count [#<post _id: 52717e7f7f11ba52d8000003, text: "twas brillig, , slithy toves did gyre , gimble in wabe.">, #<post _id: 52717e7f7f11ba52d8000007, text: "the quick brown fox jumped on lazy dog.">, #<post _id: 52717e7f7f11ba52d8000001, text: "now time men come aid of country.">] finished tests in 0.050494s, 19.8043 tests/s, 0.0000 assertions/s. 1 tests, 0 assertions, 0 failures, 0 errors, 0 skips
Comments
Post a Comment