MongoDB – Backup and Restoration
Data backup is one of the most highly required processes for any database management system as data can be lost or get corrupted to overcome these drawbacks we need database backup. Database backup is a copy of a database that already exists. In MongoDB, mongodump tool is used to take the data backup. And mongorestore tool is used to restore the backup data.
In MongoDB, mongodump tool is used to take the data backup. It simply dumps all the data stored into a dump directory of MongoDB. Backed-up data is in BSON format also known as BSON data dumps. By default, the backup is stored in mongodb’s bin\dump folder to specify a different output directory we can use the –out option. Mongodump is used in two ways with or without argument.
Without any arguments, mongodump connects with MongoDB instance on the local system on port 27017 and creates a backup of every database and every collection.
By specifying the database in the argument by which we can limit the amount of data stored in the database dump
mongodump --db databaseName --collection collectionName
To specify a different output directory we can use the –out option:
mongodump –db databaseName –collection collectionName –out c:\backup
Example 1: Backing up all the databases
Here we have 10 databases which all get backed up in the folder backupDatabase.
Note– exit mongo shell by ctrl+c to use the mongodump command.
mongodump --out c:\backupDatabase
Example 2: Backing up the specified collection
Here, we are making a backup of the collection student which contains 6 documents and is inside the GeeksForGeeks database, the backup is made inside the GFGbackup Folder.
mongodump –db GeeksForGeeks –collection students –out c:\GFGbackup
In MongoDB, mongorestore utility is used to restore the backup data. It restores the binary backup created by mongodump utility(i.e., BSON data dumps). It can restore either an entire database backup or a subset of the backup. It also restores the indexes which are created for any collection inside that database. By default, mongorestore looks for a database backup in mongodb’s bin\dump folder which is also the default folder for mongodump command for dumping the backup.
To restore all the database use –
To restore a specific collection use-
mongorestore –db databaseName –collection collectionName directory\collectionName.bson
In this example, we are using a database GeeksForGeeks which has 4 collections. We are firstly going to make a backup of student collection and then drop the student collection and then restore the student collection.
To make backup we use –
mongodump --db GeeksForGeeks --collection students --out c:\GFGbackup
The backup will be stored in c:\GFGbackup folder
Now we will drop students collection by using-
Now we will restore student collection by using –
mongorestore –db GeeksForGeeks –collection students c:\GFGbackup\GeeksForGeeks\students.bson