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 ac开发者_开发知识库tually do? Is MongoMapper intelligent enough to execute only one query with two WHERE conditions (user_id and minimum rating)?
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')})
精彩评论