Skip to content

Instantly share code, notes, and snippets.

@jasonneylon
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonneylon/fc1d12396914ab8074dd to your computer and use it in GitHub Desktop.
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
# 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