In my last post, I modified a Mongoid::Document during a migration in order to access fields that where no longer defined in the class. This time I am using the mongo ruby driver directly to migrate data.
Since I am using Mongoid in this project, I will be using it to access the dependent mongo driver. This will prevent me from having to provide mongo with a connection string in my migration. I am also using mongoid_rails_migrations to roll out the change.
Initial Design
class User
include Mongoid::Document
field :first_name
field :last_name
end
New Design
class User
include Mongoid::Document
field :name
end
Migration
class MergeUsersFirstAndLastName < Mongoid::Migration
def self.up
#get the mongo database instance from the Mongoid::Document
mongo_db = User.db
#query the collection for the fields needed for the migration
user_hashes = mongo_db.collection("users").find({}, :fields => ["first_name", "last_name"])
user_hashes.each do |user_hash|
new_name = "#{user_hash['first_name']} #{user_hash['last_name']}"
#update the new field
mongo_db.collection("users").update({"_id" => user_hash["_id"]}, {"$set" => {"name" => new_name}})
#remove old fields from collection
mongo_db.collection("users").update({"_id" => user_hash["_id"]}, {"$unset" => { "last_name" => 1, "first_name" => 1}})
end
end
end
Resources
Querying with MongoDB Ruby Driver
Updating with MongoDB Ruby Driver
About the Author