A short howto for copying all data from one MongoDB database to another.
You’ll need the mongorestore
and mongodump
tools. You can likely get these in the mongodb package.
sudo apt install mongodb
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 mongorestore
. Unfortunately mongorestore
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.
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.
mongodump --uri="mongodb+srv://<username@><uri>/<source_database_name>"
Important here that you pay attention to the --nsTo
and --nsFrom
parameters. They need to match or mongorestore
will attempt to restore into the source database. Again I put placeholders enclosed with <>
. The $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>"
Running the mongorestore
command from the same directory that your ran mongodump
should hopefully now have copied the database for you.