该解决方案结合使用 Mongodb 点符号查询$or
来提取相关评论,然后遍历它们。您必须指定最大递归级别。
请不要在现场制作中使用任何东西!如果您的数据库崩溃,我不想负责:P
# app/models/comment.rb
class Comment
include Mongoid::Document
field :content, type: String
recursively_embeds_many # this makes comment.child_comments available
# 'n' is the maximum level of recursion to check.
def self.each_matching_comment(n, q, &block)
queries = 0.upto(n).collect { |l| level_n_query(l, q) }
Comment.or(*queries).each { |c| c.each_matching_subcomment(q, &block) }
end
def self.level_n_query(n, q)
key = (['child_comments'] * n).join('.') + 'content'
return {key => q}
end
# recursive, returns array of all subcomments that match q including self
def each_matching_subcomment(q, &block)
yield self if self.content == q
self.child_comments.each { |c| c.each_matching_subcomment(q, &block) }
end
end
# hits each comment/subcomment up to level 10 with matching content once
Comment.each_matching_comment(10, 'content to match') do |comment|
puts comment.id
end
如果您希望这更快,您应该在您的评论和子评论上建立索引。