Back-up MongoDB
The mongodump
Command
mongodump
CommandWe usually backup a mongodb via
MONGO_CONNECTION_STRING="mongodb+srv://username:password@host/some_db?retryWrites=true&w=majority" mongodump --uri "$MONGO_CONNECTION_STRING" --out some/dir/mongo_backup
The Backup Files
The backup data generated looks the following:
If our database name is some_db
, then the back files lie inside mongo_backup/some_db/
.
Script to Inject Backup Data
Cloning old data into new Database
DB_USER= DB_PASSWORD= DB_HOST= DB_NAME= DB_URL="mongodb+srv://${DB_USER}:${DB_PASSWORD}@${DB_HOST}/${DB_NAME}" OPTIONS="retryWrites=true&w=majority" mongorestore --uri $DB_URL --dir ./mongo_backup/some_db
some_db/
is the directory containing all the files in the image above.
Cloning old data into the Original Database for Restoration
This time we should run with the additional flag --drop
:
mongorestore --drop --uri $DB_URL --dir ./mongo_backup/some_db
-
For every collection that we are going to restore, we first drop it.
-
Note that in this case any new collection not included in the
mongo_backup
will not be dropped.