Data backup is a highly essential and indispensable aspect for any database management system, especially keeping in mind the fact the many incidents that can lead to data loss. It is imperative to follow backup best practices whenever a database is setup, and to ensure that there is a provision for backup in case of any data loss events. Businesses prioritise robust data security which has prompted many enterprises to even err on the side of exorbitance when it comes to maintaining multiple layers of data backups.
Backing up Data in MongoDB
Initiating a data restoration and backup in MongoDB is simple and can be done by running a mongodump command on the command prompt, after which the system will dump all the server data into the dump directory of Mongo database, that has already been assigned for such purposes. It is also recommended to back up the data from remote servers as well. MongoDB also provides multiple options to limit the amount of data or create data backups of our remote server.
We can understand this better with the following illustration.
Start a MongoDB session specifying the dbpath and wait for the MongoDB client to make connections on the specified port.
After running the above command, run the mongo.exe command on a separate command prompt that will connect the client to the same port.
Once the above command has been executed, we can create a database application_db and store documents or any other records.
We can also periodically see how many databases exist on the server by using the show dbs command. There will be two databases, a local database and the second application_db which we have just created.
After running the mongodump command, we have to now start the data backup by opening a new command prompt window and then by navigating to the bin directory (here C:\Program Files\MongoDB\Server\3.2\bin) of the MongoDB. Execute ‘mongodump’ command to complete the backup of the ‘application_db’.
Upon running the above code, the records created at Step 3 will be backed up under the dump directory.
Data Restore feature in MongoDB
Data restoration in MongoDB is straightforward and is done by running mongorestore command. After executing this, the system restores all the data that is stored in the backup directory. The below example will help us understand better:
We first run a db.dropDatabase () command to drop the application_db database which was created before.
Once Step 1 is completed, the application_db database is now restored from the backup by running a mongorestore command that is done by opening a new command prompt directing to the MongoDB bin directory (here C:\Program Files\MongoDB\Server\3.2\bin). The application_db data is then restored by running the mongorestore command.
In order to know the number of databases in a mongo database server, run the show dbs command. Usually, there are two databases, i.e., local and application_db (which is restored from backup).