How to copy a MongoDB Database
A short howto for copying all data from one MongoDB database to another.
You'll need the
mongodump tools. You can likely get these in the mongodb package.
sudo apt install mongodb
⚠ Set up the new database and user
Before running the tools I strongly recommend creating a new user with readOnly access on the source database and readWrite access on
the target database. Otherwise you may accidentally overwrite the source database with
does not give any warning or confirmation before running. Luckily in my case I did not overwrite our production db, because I had limited the authz of my user to be readonly.
Creating a dump of the source database
The following command creates a
dump/<db name> directory structure, with BSON files containing the data inside.
It will ask for the password via stdin. I put placeholders enclosed with
<>, replace these with your own actual values.
Importing the dump into the target database
Important here that you pay attention to the
--nsFrom parameters. They need to match or
mongorestore will attempt to restore into the source database. Again I put placeholders enclosed with
$collection$ however are intended to work
with the pattern matching used by the mongorestore cli.
mongorestore --nsTo='<target_datbase_name>.$collection$' --nsFrom='<source_database_name>.$collection$' --uri="mongodb+srv://<username>@<uri>/<target_database_name>"
mongorestore command from the same directory that your ran
mongodump should hopefully now have copied the database for you.