4
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 和最低评分)的查询?

4

1 回答 1

1

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')})
于 2011-10-06T17:02:24.440 回答