“Dropping” a mongohq database on Heroku

I’ve used inverted commas around the word ‘dropping’ because it doesn’t look like you can drop a mongohq database – what you can do however is drop all the collections in the database. I was doing this through the add-on interface in heroku but that got tired quickly, and after some googling it looked like the solution was to write a custom rake task and drop it into lib/tasks/; the file can be named anything with a ‘.rb’ extension. The code follows: [code language=”ruby”] namespace :mdb do desc ‘Drops all the collections for the database for the current Rails.env’ task :drop => :environment do if ENV[‘MONGOHQ_URL’] uri = URI.parse(ENV[‘MONGOHQ_URL’]) conn = Mongo::Connection.from_uri(ENV[‘MONGOHQ_URL’]) DB = conn.db(uri.path.gsub(/^\//, ”)) DB.collections.each do |collection| begin collection.drop rescue puts "Can’t drop: " + collection.name end end end end end [/code] Note that the exception handler isn’t perfect and essentially all I’m doing is skipping the system collections …

Read more