MongoDB: Renaming a Database with Command Line
This short post shows you how to change the name of a MongoDB database by using the command line (MongoDB shell).
At this time, there are no official out-of-the-box tools from the MongoDB team that can help you rename a database like renaming a file on our computer. However, we can get the job done in a few minutes. Our strategy is to dump (export) the database and restore it with a different name.
An example is worth more than a thousand words. Let’s say I have a database called “old_db” and want its name to become “new_db”.
A single command is enough. What we will do is to mongodump the “old_db” database to the standard output stream and pipe it into mongorestore:
mongodump --archive --db=old_db | mongorestore --archive --nsFrom='old_db.*' --nsTo='new_db.*'
If you don’t like the first method, try the steps below:
1. Use mongodump to dump the “old_db” database to an archive:
mongodump --archive="backup_file" --db=old_db
2. Use mongorestore with –-nsFrom and –-nsTo to restore (with the name change) from the archive:
mongorestore --archive="backup_file" --nsFrom='old_db.*' --nsTo='new_db.*'
Note: The copydb and the clone commands and their mongo shell helpers db.copyDatabase() and db.cloneDatabase() are deprecated and should No longer be used in MongoDB 4.0 and beyond. That’s why mongodump is the best choice. You can find more information about the depreciation here.
If you’d like to learn more about MongoDB, take a look at the following articles:
- MongoDB: Get a Random Document from a Collection
- MongoDB: Import/Export a Database with Command Line
- Using Docker Compose with Node.js and MongoDB
You can also check out our database topic page for the latest tutorials and examples.