使用 MongoMapper 范围查询关联集合?

发布于 2024-09-27 14:03:38 字数 367 浏览 1 评论 0原文

class Comment
  include MongoMapper::Document

  scope :by_rating, lambda { |minimum| where(:rating.gte => minimum) }

  key :rating
  belongs_to :user
end

class User
  include MongoMapper::Document

  many :comments
end


User.first.comments.by_rating(3)

最后一行的查询实际上做了什么? MongoMapper 是否足够智能,可以只执行一个具有两个 WHERE 条件(user_id 和最低评分)的查询?

class Comment
  include MongoMapper::Document

  scope :by_rating, lambda { |minimum| where(:rating.gte => minimum) }

  key :rating
  belongs_to :user
end

class User
  include MongoMapper::Document

  many :comments
end


User.first.comments.by_rating(3)

What does the query on last line actually do? Is MongoMapper intelligent enough to execute only one query with two WHERE conditions (user_id and minimum rating)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

债姬 2024-10-04 14:03:38

MongoDB 做不到这一点。这需要一个它无法做到的连接。它通过具有非常可扩展的读取性能和更轻量级的查询克服了这一限制。这不是问题。您可以通过在初始化程序中设置记录器(搜索 MongoMapper.connection)来查看此行为:

 # Change as appropriate
 MongoMapper.connection = Mongo::Connection.new(
   '127.0.0.1', 27017, :logger => Logger.new(STDOUT))

然后启动 Rails 控制台,您将看到两个查询:

 User.first.comments
 MONGODB test['users'].find({}).limit(-1)
 MONGODB test['comments'].find(
   {:user_id=>BSON::ObjectId('4e8ddd6bf2c31e7001000001')})

MongoDB can't do that. That requires a join which it cannot do. It overcomes this limitation by having very scalable read performance and lighter-weight queries. It's not an issue. You can see this behavior by setting the logger in your initializer (search for MongoMapper.connection):

 # Change as appropriate
 MongoMapper.connection = Mongo::Connection.new(
   '127.0.0.1', 27017, :logger => Logger.new(STDOUT))

Then fire up your rails console and you'll see two queries:

 User.first.comments
 MONGODB test['users'].find({}).limit(-1)
 MONGODB test['comments'].find(
   {:user_id=>BSON::ObjectId('4e8ddd6bf2c31e7001000001')})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文