Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Exporting and Restoring MongoDB Databases with `mongodump` and `mongorestore`

1 min read .
Exporting and Restoring MongoDB Databases with `mongodump` and `mongorestore`

Backups are an important part of MongoDB administration. Two standard command-line tools for logical backups and restores are mongodump and mongorestore, which work with BSON data and collection metadata.

1. Back Up a Database with mongodump

Use mongodump to create a BSON backup that can later be restored.

Basic syntax:

mongodump -d <database_name> -o <backup_directory>
  • -d <database_name> → the database to back up.
  • -o <backup_directory> → the directory where the dump will be written.

Example:

mongodump -d mydatabase -o backup

This creates a backup/mydatabase directory containing the dumped collections and metadata.

2. Restore a Database with mongorestore

To restore that dump into a database, run:

mongorestore --db <database_name> <backup_directory>

For the previous example:

mongorestore --db mydatabase backup/mydatabase

This reads the BSON files from backup/mydatabase and restores them into mydatabase.

3. Work with a Specific Collection

To back up one collection, use -c or --collection:

mongodump -d mydatabase -c mycollection -o backup

To restore a single BSON file into a collection:

mongorestore --db mydatabase --collection mycollection backup/mydatabase/mycollection.bson

4. Useful Additional Options

Both tools support connection strings, authentication, remote hosts, archive files, compression, namespace filters, and other options. For production backups, prefer a connection URI so authentication and replica-set settings are explicit, and verify that your backup strategy matches the consistency guarantees your application requires.

For example:

mongodump --uri="mongodb://backup-user@db.example.internal:27017/mydatabase" --out=backup

Avoid placing real passwords directly in shell history. Use an appropriate credential mechanism for your environment.

Conclusion

mongodump and mongorestore provide a straightforward way to create logical MongoDB backups, restore data, and move collections between environments. A backup is only useful if it can be restored successfully, so include periodic restore tests in your operational process.

Related Posts

chevron-up