Wednesday, July 18, 2018

How to Backup, Restore and Migrate MongoDB Database

mongodump is a utility provided by MongoDB for creating backups of databases. This is an very useful utility and can be consider for taking backups for live servers databases very effectively. For database restore use mongorestore command. 

#1. Backup MongoDB Database (mongodump)

There are various options to take backups of mongodb database. Use mongodump command to take all databases backup or a single database backup of backup of single collection.

Backup Single Database

Use this command to take backup of a single database (named mydb) only. Backup will be created in /backup/db/ directory.
$ mongodump --db mydb --out /backup/db/  <Linux>
mongodump --db mydb --out d:\mydump  <Windows>
–db – database name to backup
–out – database backup location. This will create folder with database name.
You can specify host, port, username and password for remote databases connections backups like below.
$ mongodump --host 10.0.1.7 --port 27017 --username admin --password somepassword --db mydb --out /backup/db/

Backup All Databases

To backup all databases you just need to run following command. Here /data/db/ is location of your mongodb data directory and /backup/db is location of backup directory.
$ mongodump --out /backup/db/
You can specify host, port for remote databases.

Backup Single Collection

This command will take backup of single collection from a database. Backup file will be created in dump/mydb/ directory.
$ mongodump --collection mycollection --db mydb --out /backup/db/

#2. Restore MongoDB Database with mongorestore

mongorestore is command line tool for restoring mongodb database backup. Here /data/db/ is location of your mongodb data directory and /backup/db is location of backup directory.
$ mongorestore --db mydb --drop /backup/db/mydb
–drop – Will remove database if already exist.
You can simply move backup files to remote server and run the same command there to restore backups.

#3. MongoDB Backup Shell Script

You can easily schedule the below script in scheduler to backup databases regularly. Create a file as following
$ vi /backup/mongo-backup.sh
Add below content to file. Update database hostname, database name , username and password accordingly.
Now configure this in crontab to run daily.

No comments:

Post a Comment

Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...