0
0
MongoDBquery~5 mins

Backup and restore strategies in MongoDB

Choose your learning style9 modes available
Introduction

Backing up your data keeps it safe in case something goes wrong. Restoring helps you get your data back quickly when needed.

Before making big changes to your database to avoid data loss.
Regularly saving copies of your data to protect against hardware failure.
Recovering data after accidental deletion or corruption.
Moving your database to a new server or environment.
Testing new features without risking your real data.
Syntax
MongoDB
mongodump --uri="mongodb+srv://username:password@cluster.mongodb.net/dbname" --out=/backup/folder

mongorestore --uri="mongodb+srv://username:password@cluster.mongodb.net/dbname" /backup/folder/dbname

mongodump creates a backup of your database.

mongorestore restores data from a backup.

Examples
Backs up the database named 'mydatabase' to the specified folder.
MongoDB
mongodump --db=mydatabase --out=/backups/mydatabase_backup
Restores the 'mydatabase' database from the backup folder.
MongoDB
mongorestore --db=mydatabase /backups/mydatabase_backup/mydatabase
Backs up a cloud MongoDB database using a connection string.
MongoDB
mongodump --uri="mongodb+srv://user:pass@cluster0.mongodb.net/mydb" --out=/backups/mydb_backup
Restores the cloud MongoDB database from the backup.
MongoDB
mongorestore --uri="mongodb+srv://user:pass@cluster0.mongodb.net/mydb" /backups/mydb_backup/mydb
Sample Program

This example backs up the 'shopDB' database to a folder, then restores it into a new database called 'shopDB_restored'.

MongoDB
mongodump --db=shopDB --out=/backups/shopDB_backup
mongorestore --db=shopDB_restored /backups/shopDB_backup/shopDB
OutputSuccess
Important Notes

Always test your backups by restoring them to ensure they work.

Keep backups in a safe place, separate from your main database server.

Automate backups to run regularly without manual effort.

Summary

Backups protect your data from loss or damage.

Use mongodump to create backups and mongorestore to recover data.

Regular backups and testing help keep your data safe and available.