Renaming a Database in MongoDB

Posted in software by Christopher R. Wirz on Wed Oct 15 2014



There are many reasons to rename a Mongo Database. This should be done with caution - and backups are advised before performing any database operations.

Note: You must have Mongo 2.6 or later installed.

Database Copy method

First, connect to MongoDB's shell.

mongo

Next, copy the old content to the new database.

use old_database
db.copyDatabase('old_database', 'new_database')

Verify the new database has been copied.

use new_database
db.collection.count()

Now the old database can be removed

use old_database
db.dropDatabase()

Rename using Backup/Restore

Before using the mongo shell, use the mongodump and mongorestore commands. You may have to be an admin/root to do this.

mongodump old_database
mongorestore --db new_database ./dump/old_database

Then, connect to MongoDB's shell.

mongo

Verify the new database has been copied.

use new_database
db.collection.count()

Now the old database can be removed

use old_database
db.dropDatabase()