8

是否可以执行查询并返回嵌入的文档?

目前,我有:

class Post
  include MongoMapper::Document

  many :comments
end

class Comment
  include MongoMapper::EmbeddedDocument

  belongs_to :post

  key :author
  key :date
  key :body
end

这是一个几乎存在的查询:

Post.all("comments.date" => {"$gt" => 3.days.ago})

这将返回所有帖子对象,但不返回评论。我想我可以做类似的事情:

Post.all("comments.date" => {"$gt" => 3.days.ago}).map(&:comments)

但这将返回帖子中的所有评论。我想获得所有符合此条件的评论。也许Comment不应该嵌入。

4

1 回答 1

5

我假设您正在寻找比三天前更新的所有评论?由于您的 Comments 只是嵌入式文档,因此如果没有 Post 对象,它们就不存在,因此无法单独“查询”它们(这实际上是MongoDB 的未来功能)。但是,您可以轻松地添加一个方便的方法来帮助您:

class Comment
  include MongoMapper::EmbeddedDocument

  def self.latest
    Post.all(:conditions => {"comments.date" => {"$gt" => 3.days.ago}}).map{|p| p.comments}.flatten
  end
end

这种方法可以让您获得过去三天内已更新的所有评论,但它们不会完全按顺序排列。更好的解决方案可能是使用 Map/Reduce 来获取最新评论:

class Comment
  include MongoMapper::EmbeddedDocument

  def self.latest
    map = <<-JS
    function(){ 
      this.comments.forEach(function(comment) {
        emit(comment.created_at, comment)
      });
    }
    JS
    r = "function(k,vals){return 1;}" 
    q = {'comments.created_at' => {'$gt' => 3.days.ago}}

    Post.collection.map_reduce(m,r,:query => q).sort([['$natural',-1]])
  end
end

警告:以上是完全未经测试的代码,仅作为示例存在,但理论上应该返回按降序排序的最近三天的所有评论。

于 2010-02-28T08:20:03.417 回答