How to rename a database in MongoDB

In this article, we will see how to rename a database in MongoDB. Until MongoDB 4. or below versions, we can rename database by using db.copyDatabase(). But later versions of 4.0, it is not possible to rename a database using copyDatabase() method. The only solution is dump and restore the database.

Steps to rename a database in MongoDB:

1. Take dump of existing database. These commands has to be run from Unix level.

mongodump -d company -o /home/r2schools/mongodump/

2020-08-16T22:42:38.418-0400 writing company.accounts to /home/r2schools/mongodump/company/accounts.bson 2020-08-16T22:42:38.425-0400 writing company.hr to /home/r2schools/mongodump/company/hr.bson 2020-08-16T22:42:38.426-0400 writing company.employees to /home/r2schools/mongodump/company/employees.bson 2020-08-16T22:42:38.427-0400 done dumping company.accounts (0 documents) 2020-08-16T22:42:38.427-0400 done dumping company.employees (0 documents) 2020-08-16T22:42:38.428-0400 writing company.sales to /home/r2schools/mongodump/company/sales.bson 2020-08-16T22:42:38.442-0400 writing company.security to /home/r2schools/mongodump/company/security.bson 2020-08-16T22:42:38.457-0400 done dumping company.hr (0 documents) 2020-08-16T22:42:38.458-0400 done dumping company.sales (0 documents) 2020-08-16T22:42:38.458-0400 done dumping company.security (0 documents)

2. We have to restore the dump taken from the above.

mongorestore -d mycompanydb /home/r2schools/mongodump/company/

3. Now, connect to MongoDB server and verify the new database created or not. Run the command show dbs

show dbs

How to rename a database in MongoDB

4. If you want to keep old database, keep it. In my case I am dropping due to space issue.

use company db.dropDatabase()