All Articles

How to copy a MongoDB Database

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

⚠ 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 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.

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.

mongodump --uri="mongodb+srv://<username@><uri>/<source_database_name>"

Importing the dump into the target database

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.

Published Jan 28, 2019

Security Engineer with a dash of software. Originally from Stockholm, now in Berlin. I like to hack things.