Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Import and Export a MongoDB Database: Step-by-Step

· 4 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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)

  1. Open your terminal or command prompt.
  2. Verify MongoDB tools are installed. Run mongodump --version. If not found, install MongoDB Database Tools from the official MongoDB site.
  3. Run mongodump to export the entire database. The basic command is:
    mongodump --db your_database_name --out /path/to/backup_folder
    Replace your_database_name with your actual database name and /path/to/backup_folder with where you want the dump saved. If you omit --db, all databases are exported.
  4. 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").
  5. 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)

  1. Locate the backup folder created by mongodump. It should contain a subfolder named after the database.
  2. Run mongorestore. The basic command is:
    mongorestore --db your_database_name /path/to/backup_folder/your_database_name
    Replace your_database_name with the target database name (can differ from the original) and point to the specific database subfolder.
  3. Add authentication if needed (same flags as export).
  4. Wait for the restore to complete. The tool will recreate collections and indexes.

Exporting to JSON or CSV (Human-Readable)

  1. Use mongoexport for a single collection. Example:
    mongoexport --db mydb --collection users --out users.json
    This exports all documents in the users collection to a JSON file.
  2. Export to CSV by adding --type=csv and 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

  1. Use mongoimport. For JSON:
    mongoimport --db mydb --collection users --file users.json
    For CSV, add --type=csv --headerline to use the first line as field names:
    mongoimport --db mydb --collection users --type=csv --headerline --file users.csv
  2. Optionally drop the collection first with --drop to replace existing data instead of appending.

Common Mistakes

  • Forgetting the authentication database. Using --authenticationDatabase is required when your user is defined in a different database (e.g., admin).
  • Mixing up dump and restore paths. mongodump creates a folder, and you must point mongorestore to 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 --gzip with mongodump/mongorestore to compress the backup and save space. Add --gzip to both commands.
  • Test your backup by restoring it to a local instance before relying on it.
  • Use --archive for a single-file backup instead of a folder: mongodump --archive=backup.archive and mongorestore --archive=backup.archive.
  • For large databases, consider using --numParallelCollections to 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 admin if 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 dbAdmin or restore roles.
  • Import creates duplicate documents: If you didn't use --drop, documents are appended. Use --drop to replace the collection.
  • CSV import shows null values for some fields: The header line must exactly match field names. Use --fields with 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.