How to Migrate Data from One MongoDB Database to Another

Posted on May 8, 2024

When working with MongoDB, there are times when you need to migrate data from one database to another. This could be for backup purposes, testing, or moving a production database to a new environment. In this post, I’ll guide you through the process of dumping data from a MongoDB database named db1 and restoring it to another database named db2. This is a common task for database administrators and developers alike.

Overview of Tools Used

To perform this operation, we will use two MongoDB tools:

  • mongodump: This tool is used to export the contents of a MongoDB database into a set of BSON files.
  • mongorestore: This tool is used to import the contents of a BSON file dump into a MongoDB database.

Both tools are part of the MongoDB database tools package and can be executed from the command line.

Step 1: Dump the db1 Database

The first step in migrating your database is to create a backup of the db1 database. This is done using the mongodump command.

mongodump --db=db1 --archive=db1.dump

Here’s what each part of this command does:

  • --db=db1: This specifies that we are dumping the db1 database.
  • --out=/path/to/dump: This is the directory where the dump files will be saved. You should replace /path/to/dump with the actual path where you want the backup to be stored.

Make sure MongoDB is running, and you have the necessary permissions to access and dump the database.

Step 2: Restore the Dump to the db2 Database

Once you have a dump of the db1 database, the next step is to restore this data to the db2 database using mongorestore.

mongorestore --nsFrom='db1.*' --nsTo='db2.*' --archive=db1.dump

Let’s break down this command:

  • --nsFrom='db1.*': This tells mongorestore that we want to restore from the db1 database.
  • --nsTo='db2.*': This specifies that the target database for the restore is db2.
  • /path/to/dump/db1: This is the path to the directory containing the dumped files from db1.

This command will import all collections from the db1 database into the db2 database, effectively cloning the data.

Important Considerations

  • Authentication: If your MongoDB instance uses authentication, append --username, --password, and --authenticationDatabase options to both mongodump and mongorestore commands.
  • Data Integrity: Ensure there are no active writes to the db1 database during the dump to maintain data integrity.
  • Server Performance: Both dumping and restoring can be resource-intensive operations. Plan to perform these during off-peak hours if possible.

Conclusion

By following these steps, you can easily migrate data from one MongoDB database to another. This method is not only useful for backups but also for replicating data across different environments. Always ensure you test these operations in a development or staging environment before applying them in production to avoid any data loss.

devops mongodb