开发者

Queries on embedded documents with Mongoid/MongoDB (Rails)

I'm trying to figure out what the performance is with Mongoid when doing queries on embedded documents. I'm quite new to Mongoid and MongoDB, so if you spot anything that you think is bad practice, please let me know.

A use case:

Suppose I have a 'post' with many embedded comments in it. The comments are threaded, and each threaded comment has a parent_id field, specifying the parent comment they belong to. Example of a 'post' document:

{ 
  "_id": 1, "username": "Foo", "body": "Hi!", 
  "comments": [ 
                {"_id": 123, "body": "<3"}, 
                {"_id": 124, "body": "</3", "parent_id": "123"}, 
                ... 
              ]
}

Now suppose a post has a huge amount of comments. When I save a new comment, I want to determine with how many comments the new comment shares its parent. So 开发者_如何学GoI do this:

class Comment
  include Mongoid::Document
  field :body
  field :parent_id
  embedded_in :post, :inverse_of => :comments

  before_save :determine_amount
  def determine_amount
    return if self.parent_id.blank?
    amount = self.node.comment.where(:parent_id => self.parent_id).count

    # Do something with it...
  end
end

I'm wondering where and how Mongoid does this query, and how efficient this query is. As far as I know, the query doesn't hit the database, which makes sense because the Topic document is already loaded, and the comments are a subdocument of that.

Would anyone be so kind as to give me directions on how Mongoid handles these cases?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜