返回查询中嵌入的文档
是否可以执行查询并返回嵌入的文档?
目前,我有:
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
。
Is it possible to perform a query and return the embedded documents?
Currently, I have:
class Post
include MongoMapper::Document
many :comments
end
class Comment
include MongoMapper::EmbeddedDocument
belongs_to :post
key :author
key :date
key :body
end
Here is a query that is almost there:
Post.all("comments.date" => {"$gt" => 3.days.ago})
This will return all the post objects but not the comments. I guess I could do something like:
Post.all("comments.date" => {"$gt" => 3.days.ago}).map(&:comments)
But this would return all comments from the posts. I'd like to get all of the comments that met this condition. Perhaps Comment
should not be embedded.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我假设您正在寻找三天前更新的所有评论?由于您的评论只是嵌入文档,如果没有 Post 对象,它们就不存在,因此无法单独“查询”它们(这实际上是 MongoDB 的未来功能)。但是,您可以轻松添加一个方便的方法来帮助您:
此方法将为您提供过去三天内更新的所有评论,但它们不会完全按顺序排列。更好的解决方案可能是使用 Map/Reduce 来提取最新评论:
注意:以上是完全未经测试的代码,仅作为示例存在,但理论上应返回按降序排序的过去三天的所有评论。
I assume you're looking for all comments newer than three days ago? Since your Comments are just embedded documents, they do not exist without the Post object so there's no way to "query" them separately (this is actually a future feature of MongoDB). However, you could easily add a convenience method to help you out:
This method would get you all of the comments that have been updated in the last three days but they would not entirely be in order. A better solution might be to use Map/Reduce to pull the latest comments:
Caveat: the above is completely untested code and just exists as an example, but theoretically should return all comments from the last three days sorted in descending order.