Dump and restore mongodb

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://username:[email protected]:27015/my_remote_db

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 🙅‍♀️.

#!/bin/bash

MONGO_SOURCE_URI="mongodb://user:[email protected]:17970/source_db_name" # 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://user:[email protected]:17970/destination_db_name" # 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 -v --archive --uri=$MONGO_SOURCE_URI | mongorestore -v --archive -d $MONGO_DESTINATION_DB_NAME --nsFrom $NS_FROM --nsTo $NS_TO --uri=$MONGO_DESTINATION_URI

Duplicate/copy/backup a database on local mongodb

Dumping and restoring from disk in between:

mongodump -d "db-name" -v -o mongodb-dump/
mongorestore -d "new-db-name" --drop -v mongodb-dump/db-name

Or we can use piping to skip persisting the db on disk:

mongodump -d "db-name" -v --archive | mongorestore --nsFrom "db-name.*" --nsTo "new-db-name.*" -v --drop --archive

Notes about the options:

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

Updated 2018-05-24