2012-03-27 33 views

回答

1

當它是belongs_to關係時,您可以打開identity map併爲您的主文檔運行兩次查詢,然後爲所有關聯文檔運行一次查詢。這是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有syntax for eager loading,但它的工作原理基本上是相同的方式。)

+1

而且,如果它是一個Rails應用程序有大量的對象,可以GC約束等的熱切裝載會降低查詢但你的迴應時間可能並沒有太大的改善。在我們的一個應用程序中,有大約400個對象被加載,這種熱切的加載只會使我們的請求響應時間縮短約10%。在該請求期間禁用GC再向我們購買了35%。 – 2012-03-27 20:31:34

+0

謝謝,我正在尋找什麼。 – zoli 2012-03-27 21:28:12

相關問題