Problem Statement

In this post, we will learn how to take backup from MongoDB instance, and restore that to another MongoDB instance.

Tools Required

The tool you require are:

  • mongodump - To take backup
  • mongorestore - To restore

Taking Backup from a Running MongoDB instance

Run following command to take backup of a specific database

mongodump --db YOUR_DB_NAME --out YOUR_TARGET_FOLDER

This will take backup of your passed database name, to the passed folder. It will create a new folder under the path passed, and its name will be the name of your DB.

If your MongoDB instance runs on another port

By default, MongoDB instance runs on port 27017. Let us assume, it is running on port: 27020, and hostname is localhost.

Run following command:

mongodump --host localhost:27020 --db YOUR_DB_NAME --out YOUR_TARGET_FOLDER

To restore backup to a running instance of MongoDB

Run following command, if your instance is running on default port i.e. 27017:

mongorestore --db YOUR_DB_NAME YOUR_TARGET_FOLDER/YOUR_DB_NAME

If your MongoDB instance runs on another port

mongorestore --uri mongodb://localhost:27020 --db YOUR_DB_NAME YOUR_TARGET_FOLDER/YOUR_DB_NAME

Enjoy!