Created
July 24, 2010 23:38
-
-
Save banker/489098 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# with multiple collections + commands for renaming back the collections | |
require 'mongo' | |
# Stop writing to your database. | |
# Then, for each collection: | |
# Specify the DB and COLLECTION you want to convert. | |
# Will insert all modified documents into a new collection | |
# called 'new_' + old_collection_name. | |
# Then you can delete the old collection and rename the new one | |
# once you've verified that the new collection is correct. | |
DB = "" # Put your db name here | |
COLLECTIONS = [] # Put a list of collection names here | |
def convert_ids(obj) | |
if obj.is_a?(String) && obj =~ /^[a-f0-9]{24}$/ | |
BSON::ObjectID(obj) | |
elsif obj.is_a?(Array) | |
obj.map do |v| | |
convert_ids(v) | |
end | |
elsif obj.is_a?(Hash) | |
obj.each do |k, v| | |
obj[k] = convert_ids(v) | |
end | |
else | |
obj | |
end | |
end | |
def convert_collection collection | |
original_collection = @db[collection] | |
new_collection = @db['new_' + collection] | |
puts "db.#{collection}.renameCollection('#{original_collection.name}_original')" | |
puts "db.new_#{collection}.renameCollection('#{original_collection.name}')" | |
new_collection.drop | |
original_collection.find({}, :timeout => false, :sort => "_id") do |c| | |
c.each do |doc| | |
new_doc = convert_ids(doc) | |
new_collection.insert(new_doc, :safe => true) | |
end | |
end | |
end | |
@con = Mongo::Connection.new | |
@db = @con[DB] | |
COLLECTIONS.each do |collection| | |
convert_collection collection | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. We'll just keep your version here so that people have a few different examples.
Kyle