2013-09-24 150 views
0

輸入代碼hereI「米目前正在運行通過mongoid MongoDB的一個Rails應用程序。比方說,我有兩個集合,文章和評論,他們正在通過一個HABTM關係聯繫在一起,我想喜歡選擇具有最多評論的帖子,我想這樣做的方式是計算每個崗位和order by comments.count DESC的意見。我不知道怎麼算的意見對每個職位的數量通過這種「僞場」一列添加到帖子結果就像count(comments) AS comments_count在SQL和訂單。計數的hasMany關係/ mongoid

對這個有什麼想法?

感謝

編輯,尋找與此相關的其他人的答案,我已經試過:

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); 
    } 
); 

我越來越

{ 
"result" : [{ 
     "_id" : null, 
     "datasets_count" : 1 
    }], 
"ok" : 1 
} 
+0

對於高性能聚合是值得擁有嵌入到帖子的文件或目錄支持其計數的意見。你有什麼?這些集合如何相互鏈接?你能提供文件樣本嗎? – viktortnk

回答

2

MongoDB中的聚合框架對分組運營商,總結和分類。 以下是如何分組,計數和評論數排序的職位工作的例子。 希望這是你想要的東西,它可以幫助。

模型/ post.rb

class Post 
    include Mongoid::Document 
    has_many :comments 
    field :text, type: String 
end 

模型/ comment.rb

class Comment 
    include Mongoid::Document 
    belongs_to :post 
    field :text, type: String 
end 

測試/單元/ post_test.rb

require 'test_helper' 
require 'pp' 
class PostTest < ActiveSupport::TestCase 
    def setup 
    Post.delete_all 
    Comment.delete_all 
    end 
    test "posts ordered by comment count" do 
    [ [ "Now is the time for all good men to come to the aid of their country.", 
     [ "Tally ho!" ] ], 
     [ "Twas brillig, and the slithy toves did gyre and gimble in the wabe.", 
     [ "Off with their heads!", 
      "The time has come, the walrus said.", 
      "Curiouser and curiouser." ] ], 
     [ "The quick brown fox jumped over the lazy dog.", 
     [ "The typewriter is mightier than the sword.", 
      "Dachshund is a badger dog." ] ] 
    ].each do |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 do |post_id_count| 
     Post.find(post_id_count['_id']) 
    end 
    puts 
    pp result 
    end 
end 

耙測試

運行測試:

[1/1] PostTest#test_posts_ordered_by_comment_count 
[#<Post _id: 52717e7f7f11ba52d8000003, text: "Twas brillig, and the slithy toves did gyre and gimble in the wabe.">, 
#<Post _id: 52717e7f7f11ba52d8000007, text: "The quick brown fox jumped over the lazy dog.">, 
#<Post _id: 52717e7f7f11ba52d8000001, text: "Now is the time for all good men to come to the aid of their country.">] 
Finished tests in 0.050494s, 19.8043 tests/s, 0.0000 assertions/s. 
1 tests, 0 assertions, 0 failures, 0 errors, 0 skips