我有一个场景,我需要更新 mongodb 中的一些 7k 记录。查询是
Document.all.each do |d|
d.pages_enabled_count = d.pages.where(:disabled => false).count
d.pages_enabled_to_query_count = d.pages.where(:disabled => false , :to_query => true).count
d.pages_enabled_to_rescan_count = d.pages.where(:disabled => false , :to_rescan => true).count
d.pages_enabled_to_retag_count = d.pages.where(:disabled => false , :to_retag => true).count
d.save
end
看起来这个查询需要超过 2 小时!!一次更新大约需要 1.6 秒。有什么方法可以优化这个?
MONGODB (388.3ms) test['$cmd'].find({"count"=>"pages", "query"=>{:deleted_at=>nil,
"document_id"=>BSON::ObjectId('51cd1c435329b64899000035'), :disabled=>false}, "fields"=>nil}).limit(-1)
MONGODB (388.5ms) test['$cmd'].find({"count"=>"pages", "query"=>{:deleted_at=>nil, "document_id"=>BSON::ObjectId('51cd1c435329b64899000035'), :disabled=>false, :to_query=>true}, "fields"=>nil}).limit(-1)
MONGODB (408.0ms) test['$cmd'].find({"count"=>"pages", "query"=>{:deleted_at=>nil, "document_id"=>BSON::ObjectId('51cd1c435329b64899000035'), :disabled=>false, :to_rescan=>true}, "fields"=>nil}).limit(-1)
MONGODB (390.9ms) test['$cmd'].find({"count"=>"pages", "query"=>{:deleted_at=>nil, "document_id"=>BSON::ObjectId('51cd1c435329b64899000035'), :disabled=>false, :to_retag=>true}, "fields"=>nil}).limit(-1)
MONGODB (0.9ms) test['users'].find({"owned_document_id"=>BSON::ObjectId('51cd1c435329b64899000035')}).limit(-1).sort([[:_id, :asc]])
MONGODB (0.1ms) test['documents'].update({"_id"=>BSON::ObjectId('51cd1c435329b64899000035')}, {"$set"=>{"pages_enabled_count"=>18, "pages_enabled_to_query_count"=>0, "pages_enabled_to_rescan_count"=>0, "pages_enabled_to_retag_count"=>0, "updated_at"=>2013-08-20 04:35:47 UTC}})