【问题标题】:migrating mongo data with rake-like tasks使用类似 rake 的任务迁移 mongo 数据
【发布时间】:2011-12-01 18:29:55
【问题描述】:

我有一个 rake 任务,旨在将遗留数据库字段迁移到 Hash

task :degrees => :environment do
  Person.all.each do |p|
    if p['degree1'] || p['degree2']
      p.degrees = {}
      p.degrees["first"] = p['degree1'] == "Other" ? p['degree1_other'] : p['degree1'] 
      p.degrees["second"] = p['degree2'] == "Other" ? p['degree2_other'] : p['degree2']
      p.save
    end
  end
end

问题是 mongo 和 ruby​​ 分别占用 80% 和 20% CPU 的速度非常慢。

对于更简单的迁移,我可以像这样使用 mongo 更新:

db.people.update({},{$rename : {"url" : "website"}}, false, true)

这运行得非常快。有什么方法可以将上述 rake 任务翻译成 mongo 更新或 shell 脚本?

【问题讨论】:

  • 如果您想用 Ruby 编写并轻松将其移植到 js mongo,请从调试器中获取 mongo 命令(如果您设置为调试级别)。

标签: ruby-on-rails ruby mongodb mongoid


【解决方案1】:

我创建了一个shell script

db.people.update({degree1:"Other"}, { $rename : { "degree1_other" : "degree1" } }, false, true )
db.people.update({degree2:"Other"}, { $rename : { "degree2_other" : "degree2" } }, false, true )
db.people.update({degree3:"Other"}, { $rename : { "degree3_other" : "degree3" } }, false, true )

db.people.find({degrees:null}).forEach( function (doc) {
    doc.degrees = { "first" : doc.degree1, "second" : doc.degree2, "third" : doc.degree3 };
    db.people.save(doc);
});

db.people.update({degree1: {$exists : true}},{$unset:{degree1:1}},false,true)
db.people.update({degree1_other: {$exists : true}},{$unset:{degree1_other:1}},false,true)
db.people.update({degree2: {$exists : true}},{$unset:{degree2:2}},false,true)
db.people.update({degree2_other: {$exists : true}},{$unset:{degree2_other:2}},false,true)
db.people.update({degree3: {$exists : true}},{$unset:{degree3:3}},false,true)
db.people.update({degree3_other: {$exists : true}},{$unset:{degree3_other:3}},false,true)

它会在几秒钟内运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 2021-08-28
    • 2015-10-05
    • 2021-01-14
    • 1970-01-01
    相关资源
    最近更新 更多