Back to index

Dump and restore mongodb

Published by bolmaster2

When you wanna load your remote production mongodb into your local one. Two easy commands. Both the --uri option and --nsFrom/--nsFrom options was added in mongodb 3.4.16. So if you are on an old version, those commands are not gonna work.

Dump a remote mongodb

mongodump --uri=mongodb://

Without any options, it puts the database under the directory dump/my_remote_db. You can specify it with the --out option.

Load it into your local mongodb

mongorestore -d my_local_db 'dump/my_remote_db'

If you prefer a one liner

…or you can’t or don’t want to store a temp file with the dump. Or some other reason. The almighty | (pipe) to the rescue!

This maybe looks a bit more scary because it’s more lines of code. But it’s mostly variables you need to set. Like URI’s to the db’s and such. And the db names. I’ve populated all of the variables for you to get a grasp of what you need to supply. It’s usually easier to understand that way. In the real world, maybe those variables is environment variables and you can actually just issue one command 🙅‍♀️.


MONGO_SOURCE_URI="mongodb://" # URI to the source I want to copy
MONGO_DESTINATION_DB_NAME="destination_db_name" # Name of the db where it's gonna be copied to
NS_FROM="source_db_name.*" # Previous namespace/db name on the source
NS_TO="$MONGO_DESTINATION_DB_NAME.*" # New namespace/db name on the destination
MONGO_DESTINATION_URI="mongodb://" # URI to the destination

# With the --nsFrom and --nsTo options we change the name of the database
# which is sometimes what you want and sometimes not. If not, just remote those two options

mongodump --verbose --archive --uri=$MONGO_SOURCE_URI | mongorestore --verbose --archive -d $MONGO_DESTINATION_DB_NAME --nsFrom $NS_FROM --nsTo $NS_TO --uri=$MONGO_DESTINATION_URI

☝️ Updated 2018-05-24

If you want to do the same thing for postgres, check this out