In earlier versions of MongoDB, you could use the copyDB
command or its helper method, db.copyDatabase()
to copy a database.
MongoDB has since deprecated these. Also, starting in version 4.2, MongoDB has removed the copydb
command, and therefore also the db.copyDatabase()
method, which means that you can’t use them even if you wanted to if you’re using MongoDB 4.2 or later.
Fortunately, there’s another way to copy a MongoDB database.
Check for MongoDB Database Tools
In MongoDB, you can clone a database using the MongoDB Database Tools. Specifically, you can use mongodump
and mongorestore
.
The MongoDB Database Tools are a suite of command-line utilities for working with MongoDB.
If you’re not sure whether you have the MongoDB Database Tools installed, try running the following commands in your Terminal or Command Prompt to check:
mongodump --version
mongorestore --version
That specifically checks for the mongodump
and mongorestore
versions.
If you don’t have them, you can use the installation instructions over at the MongoDB website to install MongoDB Database Tools on to your system.
Example of Cloning a Database
You need to run mongodump
and mongorestore
from your system’s command line (e.g. a new Terminal or Command Prompt window). Don’t run it from the mongo
shell.
Here’s an example of code that clones a database:
mongodump --archive --db=PetHotel | mongorestore --archive --nsFrom='PetHotel.*' --nsTo='PetHouse.*'
In this case, we backup the PetHotel
database, then restore all of its collections to a database called PetHouse
. In other words, we cloned the PetHotel
database as PetHouse
.
This uses mongodump
to create a backup file of the database, then mongorestore
to restore that database under a different name. We did this by dumping the database to the standard output stream and piping into mongorestore
.
Here’s what each parameter does:
Parameter | Description |
---|---|
--archive | Writes the output to a specified archive file or, if the archive file is unspecified, writes to the standard output (stdout ). In our case, the archive file is unspecified, so it wrote to the standard output. |
--db | Specifies a database to backup. In this case, we backup the PetHotel database. |
--nsFrom | Specifies the collection in the dump file. The asterisk wildcard (* ) specifies all collections. |
--nsTo | Specifies the collection name that should be used in the restored database. |
You can also use mongodump
to dump all databases. To do that just run mongodump
without any arguments. However, when you do that, it doesn’t include the local
and config
databases in its dump.