In this Post, we’ll walk through how to back up and restore a MongoDB database using the mongodump
and mongorestore
tools.
MongoDB Backup and Restore Using Utility
MongoDB Backup
Though MongoDB is a popular NoSQL database and known for its flexibility and scalability. However, with great data comes great responsibility. Regular backups are crucial to ensure data safety and disaster recovery. MongoDB offers several tools for this, and one of the most widely used is the mongodump
utility.
What is mongodump?
mongodump
is a command-line tool that creates a binary export (BSON format) of the contents of a MongoDB database. It connects to a running MongoDB instance and dumps data into specified directories.
Backup with mongo dump commands
Basic Syntax mongodump --uri="mongodb://host:port"
This command dumps all databases from the local MongoDB instance into a default dump
directory.
mongodump --uri="mongodb://localhost:27017" --db=mydatabase
Backup a Specific Collection
mongodump --uri="mongodb://localhost:27017" --db=mydatabase --collection=mycollection
Specify Output Directory
mongodump --uri="mongodb://localhost:27017" --out=/path/to/backup
Include Authentication
mongodump --uri="mongodb://username:password@localhost:27017" --authenticationDatabase=admin --db=mydatabase
MongoDB Restore
Restoring data in MongoDB typically involves using the mongorestore
utility. Here's a concise guide to help you do it, based on different use cases.
What is mongorestore?
mongorestore
is the complementary tool that imports content from a binary database dump into a MongoDB instance, restoring the data as it was when the dump was created.
Restore with mongorestore
Basic Syntax
mongorestore --uri="mongodb://host:port" /path/to/backup
Restore a Specific Database
mongorestore --uri="mongodb://localhost:27017" --db=mydatabase /path/to/backup/mydatabase
Restore a Collection
mongorestore --uri="mongodb://localhost:27017" --db=mydatabase --collection=mycollection /path/to/backup/mydatabase/mycollection.bson
If Auth Is Enabled
mongorestore --username <user> --password <pass> --authenticationDatabase admin /path/to/backup/
Restore to a Remote Server
mongorestore --host <hostname or IP> --port <port> /path/to/backup/
Summary
Backing up and restoring MongoDB databases using mongodump and mongorestore is straightforward and effective for most use cases, these tools are essential parts of a MongoDB administrator’s toolkit.
Thanks