0
0
MongodbHow-ToBeginner · 3 min read

How to Export Data to CSV from MongoDB Easily

You can export data from MongoDB to a CSV file using the mongoexport tool with the --type=csv option. Specify the database, collection, and fields to export, then run the command in your terminal to create the CSV file.
📐

Syntax

The basic syntax for exporting MongoDB data to CSV is:

  • mongoexport: The command-line tool to export data.
  • --db: The database name.
  • --collection: The collection name.
  • --type=csv: Specifies CSV output format.
  • --fields: Comma-separated list of fields to include.
  • --out: The output CSV file path.
bash
mongoexport --db=<database> --collection=<collection> --type=csv --fields=<field1>,<field2> --out=<filename>.csv
💻

Example

This example exports the name and age fields from the users collection in the testdb database to a file named users.csv.

bash
mongoexport --db=testdb --collection=users --type=csv --fields=name,age --out=users.csv
Output
Exported 3 records to users.csv
⚠️

Common Pitfalls

Common mistakes when exporting to CSV include:

  • Not specifying --fields, which exports all fields but may include unwanted data.
  • Using incorrect field names that do not exist in the collection.
  • Running mongoexport without proper permissions or connection settings.
  • Forgetting to specify --type=csv, which defaults to JSON output.

Always check your field names and ensure the MongoDB server is accessible.

bash
mongoexport --db=testdb --collection=users --out=users.csv
# This exports JSON, not CSV

mongoexport --db=testdb --collection=users --type=csv --fields=name,age --out=users.csv
# Correct CSV export
📊

Quick Reference

OptionDescription
--dbName of the database
--collectionName of the collection
--type=csvExport format as CSV
--fieldsComma-separated list of fields to export
--outOutput file path for the CSV

Key Takeaways

Use mongoexport with --type=csv to export MongoDB data as CSV files.
Always specify the fields you want to export with --fields to control output.
Check your field names carefully to avoid empty or incorrect CSV columns.
Without --type=csv, mongoexport outputs JSON by default.
Ensure you have access to the MongoDB server and correct permissions before exporting.