count在mongodb / mongoid中有很多关系

时间:2013-09-24 18:02:42

标签: mongodb mongoid

在这里输入代码我“目前正在通过mongoid运行mongodb的rails应用程序。假设我有两个集合,帖子和评论,并且它们是通过HABTM关系链接的,我想选择有的帖子最多的评论,我认为这样做的方法是通过comments.count DESC计算每个帖子和订单的评论。我不知道如何计算每个帖子的评论数量,在帖子中添加一列结果类似于SQL中的count(comments) AS comments_count,并按此“伪字段”排序。

对此有何想法?

由于

编辑,看着其他与此相关的答案,我试过了:

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
}

1 个答案:

答案 0 :(得分: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

rake test

正在运行测试:

[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