Last active
August 29, 2015 14:02
-
-
Save jasonneylon/fc1d12396914ab8074dd to your computer and use it in GitHub Desktop.
Method to rename a collection in mongo db which works even if the target collection exists
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
# version of rename collection that drops the existing collection if present. | |
# the standard rename method on the collection object provided by the driver | |
# throws an exception if the target collection exists | |
# http://docs.mongodb.org/manual/reference/command/renameCollection/ | |
def self.rename_collection(db, old_name, new_name) | |
cmd = BSON::OrderedHash.new | |
database_name = db.name | |
cmd[:renameCollection] = "#{database_name}.#{old_name}" | |
cmd[:to] = "#{database_name}.#{new_name}" | |
cmd[:dropTarget] = true | |
puts "Renaming collection #{old_name} to #{new_name}" | |
db.connection.db("admin").command(cmd) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment