This blog post will discuss the process of backing up and restoring a MongoDB database using the built-in commands and tools provided by MongoDB. To perform a data backup in MongoDB, the mongodump tool is utilized. This tool effectively dumps all the data stored in the database into a designated dump directory. On the other hand, the mongorestore command allows you to restore the backups created by the mongodump command back into a MongoDB instance.

Mongodump:

Mongodump is a backup solution for small MongoDB instance due to its ease of use and portability.

syntax: mongodump –db databasename –collection name –out locationpath

Step 1: To begin, we must establish a connection with the mongo shell command “mongosh” and proceed to create the sample database along with a few collections (table).

Step 2: Create a designated folder to store the backup files, specify the file path, and proceed with executing the mongodump command.

A backup folder has been created at the designated location: (D:\Mongo_backup)

The backup files have been generated on the designated path. The backup process has now concluded.

Mongorestore:

The Mongorestore command is a command that is closely related to the Mongodump command. It serves the purpose of restoring the backups created by the Mongodump command into a MongoDB Instance.

Syntax: mongorestore <options> <connection-string> <directory or file to restore>

Step 3: Drop the sample database that has been created using the command “db.dropDatabase()”. You should connect to the database before you execute the drop command.

Step 4: Execute “mongorestore” command from the backup file location.

Step 5: Verify whether the database is restored or not.

Step 6: Here is the other method to backup only the collections (tables) use the below commands

Syntax: mongodump –db=<db_name> –collection=<collection_name> –out=data/

Command: Mongodump –db  hrms –collection hr

Step 7: Drop the single collections (table) using the command “db.hr.drop()”

Step 8: Restore the collections using the below command

Syntax: mongorestore –db db_name –collection collection_name dump/dbname/collection.bson

Mongorestore –db hrms –collection hr D:\Mongo_backup\collections_bk\dump\hrms\hr.bson

In this blog post, we have discussed the backup and restore methods for small databases. However, when dealing with large databases, it is recommended to utilize alternative backup tools that are available in MongoDB.

Recent Posts

Start typing and press Enter to search