在MongoMapper中是否有一种方法可以实现与AR包含方法类似的行为?

MongoMapper中是否有与此类似的function:

class Model < ActiveRecord::Base belongs_to :x scope :with_x, includes(:x) end 

运行Model.with_x时,这可以避免对X进行N次查询.MongoMapper中是否有类似的function?

当它是belongs_to关系时,您可以打开身份映射并运行两个查询,一个用于主文档,一个用于所有相关文档。 这是你可以做的最好的,因为Mongo不支持连接。

 class Comment include MongoMapper::Document belongs_to :user end class User include MongoMapper::Document plugin MongoMapper::Plugins::IdentityMap end @comments = my_post.comments # query 1 users = User.find(@comments.map(&:user_id)) # query 2 @comments.each do |comment| comment.user.name # user pulled from identity map, no query fired end 

(Mongoid有一个急切加载的语法 ,但它的工作方式基本相同。)