w3resource

Export all Collections in MongoDB Database with mongodump

How to Export all Collections in a MongoDB Database?

In MongoDB, you can export all collections in a database using the mongodump utility, which is included in MongoDB's suite of command-line tools. The mongodump command allows you to back up an entire database, including all collections, into a BSON file format. This format is efficient and compatible with mongorestore, which you can use to restore the data back into MongoDB if needed.

Description:

To export all collections in a MongoDB database, you can use the mongodump command, which exports an entire database, including its collections, into BSON files. This method is ideal for creating backups, migrating data, or transferring databases between servers. The mongodump command can export data either locally or from a remote MongoDB instance by specifying connection details.

Syntax:

The basic syntax to export all collections in a MongoDB database is:

mongodump --db <database_name> --out <output_directory>

Explanation:

  • <database_name>: The name of the database you want to export.
  • <output_directory>: The directory where the exported files will be saved.

Example:

Below is an example command that exports all collections from a database named myDatabase to a directory named backup:

Code:

# Export all collections in the 'myDatabase' database to the 'backup' directory
mongodump --db myDatabase --out /path/to/backup

Explanation:

  • mongodump
    This command is used to export MongoDB data into BSON format, which is MongoDB's binary representation of JSON-like documents.
  • --db myDatabase
    The --db option specifies the database name (myDatabase in this example) from which all collections will be exported.
  • --out /path/to/backup
    The --out option defines the directory path where the exported files will be saved. Within this directory, MongoDB will create a folder named after the database (myDatabase) containing BSON files for each collection.

Additional Options:

  • Specify Host and Port: You can export from a remote MongoDB instance by adding --host <host>:<port>.
    mongodump --db myDatabase --host <host>:<port> --out /path/to/backup
    
  • Authentication: If your MongoDB instance requires authentication, include --username
    <username> --password <password>.
    

Restoration

To restore the exported database later, you can use mongorestore:

mongorestore --db myDatabase /path/to/backup/myDatabase

This command will restore all collections in the myDatabase database from the backup directory.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/mongodb/snippets/how-to-export-all-collections-in-a-mongodb-database.php