1

我有一个场景,我需要更新 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}})
4

1 回答 1

0

你可以做

Document.all.each do |d|
  d.update({ :pages_enabled_count => d.pages.where(:disabled => false).count,
             :pages_enabled_to_query_count => d.pages.where(:disabled => false, :to_query => true).count,
             :pages_enabled_to_rescan_count => d.pages.where(:disabled => false, :to_rescan => true).count,
             :pages_enabled_to_retag_count => d.pages.where(:disabled => false, :to_retag => true).count
          })
end

这将加快一点,因为没有callbacksvalidations将运行。

如果这是一次性活动,您可以考虑在Mongodb不使用的情况下进行mongoid

于 2013-08-20T09:17:15.613 回答