Import and Export a MongoDB Database: Step-by-Step
In this article
This guide walks you through exporting a MongoDB database to a portable format and importing it into another MongoDB instance. You'll use the built-in mongodump and mongorestore tools (for binary backups) and mongoexport/mongoimport (for JSON/CSV data). No prior experience is needed, but you should have MongoDB installed and running.
What You'll Need
- MongoDB installed locally or access to a remote MongoDB instance (connection string with credentials if authentication is enabled).
- Command-line access (Terminal on macOS/Linux, Command Prompt or PowerShell on Windows).
- Sufficient disk space for the exported files (roughly the size of your database).
- Basic familiarity with navigating directories and running commands.
Step-by-Step
Exporting a MongoDB Database (Binary Backup)
- Open your terminal or command prompt.
- Verify MongoDB tools are installed. Run
mongodump --version. If not found, install MongoDB Database Tools from the official MongoDB site. - Run mongodump to export the entire database. The basic command is:
mongodump --db your_database_name --out /path/to/backup_folder
Replaceyour_database_namewith your actual database name and/path/to/backup_folderwith where you want the dump saved. If you omit--db, all databases are exported. - Add authentication if needed. If your MongoDB requires credentials, include:
--username your_user --password your_password --authenticationDatabase admin
(Or use the full connection string:--uri "mongodb://user:pass@host:port/dbname"). - Wait for the command to finish. You'll see progress messages. The output folder will contain a subfolder per database, with BSON and JSON metadata files.
Importing a MongoDB Database (Binary Restore)
- Locate the backup folder created by
mongodump. It should contain a subfolder named after the database. - Run mongorestore. The basic command is:
mongorestore --db your_database_name /path/to/backup_folder/your_database_name
Replaceyour_database_namewith the target database name (can differ from the original) and point to the specific database subfolder. - Add authentication if needed (same flags as export).
- Wait for the restore to complete. The tool will recreate collections and indexes.
Exporting to JSON or CSV (Human-Readable)
- Use mongoexport for a single collection. Example:
mongoexport --db mydb --collection users --out users.json
This exports all documents in theuserscollection to a JSON file. - Export to CSV by adding
--type=csvand specifying fields:mongoexport --db mydb --collection users --type=csv --fields name,email --out users.csv
Note: CSV only works with flat documents; nested objects are flattened or omitted.
Importing from JSON or CSV
- Use mongoimport. For JSON:
mongoimport --db mydb --collection users --file users.json
For CSV, add--type=csv --headerlineto use the first line as field names:mongoimport --db mydb --collection users --type=csv --headerline --file users.csv
- Optionally drop the collection first with
--dropto replace existing data instead of appending.
Common Mistakes
- Forgetting the authentication database. Using
--authenticationDatabaseis required when your user is defined in a different database (e.g.,admin). - Mixing up dump and restore paths.
mongodumpcreates a folder, and you must pointmongorestoreto the database subfolder, not the parent folder. - Using mongoexport for a full database. It only works on one collection at a time. For a whole database, use
mongodump. - CSV with nested documents. CSV doesn't handle arrays or nested objects well—use JSON for complex data.
- Not checking disk space. A large database can fill up your disk during export, causing failure.
Tips
- Use
--gzipwith mongodump/mongorestore to compress the backup and save space. Add--gzipto both commands. - Test your backup by restoring it to a local instance before relying on it.
- Use
--archivefor a single-file backup instead of a folder:mongodump --archive=backup.archiveandmongorestore --archive=backup.archive. - For large databases, consider using
--numParallelCollectionsto speed up restore (default is 4). - Always specify the database name explicitly to avoid accidentally exporting all databases.
Troubleshooting
- Command not found: Ensure MongoDB Database Tools are installed and in your PATH. On Windows, you may need to run from the installation bin directory.
- Authentication failed: Double-check username, password, and the authentication database. Use
--authenticationDatabase adminif your user is created there. - Connection refused: MongoDB isn't running or is on a different host/port. Check with
mongosh --eval "db.runCommand({ping:1})". - Restore fails with "Cannot create collection" errors: The target database may have conflicting indexes or the user lacks privileges. Ensure your user has
dbAdminorrestoreroles. - Import creates duplicate documents: If you didn't use
--drop, documents are appended. Use--dropto replace the collection. - CSV import shows null values for some fields: The header line must exactly match field names. Use
--fieldswith mongoimport if the header is missing or incorrect.
Frequently Asked Questions
Can I export only a subset of documents?
Yes, use --query with mongoexport to filter documents, e.g., --query '{"status": "active"}'.
Does mongodump lock the database?
No, it creates a consistent snapshot without locking writes. However, for point-in-time consistency across all collections, consider using MongoDB Atlas or a replica set.
Can I import a JSON file exported from a different MongoDB version?
Generally yes, but there may be compatibility issues with new data types (e.g., decimal128). Test on a staging instance first.
What's the difference between mongodump and mongoexport?
mongodump creates a binary BSON backup that includes indexes and is faster for large data. mongoexport outputs human-readable JSON/CSV for one collection, useful for migrations to other systems.
How do I export a remote database?
Use the --host and --port flags or a full --uri connection string, e.g., mongodump --uri "mongodb://user:pass@remote-host:27017/mydb".
Can I schedule automatic backups?
Yes, you can create a cron job (Linux/macOS) or a scheduled task (Windows) that runs the mongodump command at regular intervals. Ensure the output folder is rotated to avoid disk full.