MongoDB Backup and Restore

Useful commands to backup and restore a MongoDB database. See the MongoDB docs for more information.

Backup

mongodump -h localhost:27017 -d <database-name> -o <path\to\store\backup>
# example
mongodump -h localhost:27017 -d my-db -o c:\data\mongo\2021-11-08-my-db-backup
 
# Cloud/URI-based export
# -v is verbose
mongodump --uri "mongodb+srv://<username>@<hostname>" -o c:\data\mongo\backups\folder\name -v

Restore

cd <directory containing the backup data>
mongorestore --host localhost --port 27017 --username USER_NAME --password SAMPLE_PASSWORD --db DATABASE_NAME .
 
# Use /dir to specify a directory containing the dump to restore
mongorestore /dir backup1
 
# Use /drop to drop existing collections before restoring
mongorestore /drop
 
# Use -d specify which database to restore to
mongorestore -d my-db
 
# Complex example with specified db, dir, and drop
mongorestore --host localhost --port 27017 -d my-db /dir db-backup-2023.01.18 /drop