How to Use mongoexport: Export MongoDB Data Easily
Use
mongoexport to export data from a MongoDB collection to a JSON or CSV file. The basic command includes specifying the database, collection, and output file with options like --db, --collection, and --out.Syntax
The basic syntax of mongoexport is:
--db: The database name to export from.--collection: The collection name to export.--out: The file path to save the exported data.--jsonArray: (Optional) Export data as a JSON array.--type: (Optional) Specify output format:json(default) orcsv.--fields: (Optional) For CSV, specify which fields to export.
bash
mongoexport --db=<database> --collection=<collection> --out=<file> [--jsonArray] [--type=csv] [--fields=field1,field2]Example
This example exports the users collection from the mydb database to a JSON file named users.json. It uses --jsonArray to export the data as a JSON array.
bash
mongoexport --db=mydb --collection=users --out=users.json --jsonArray
Output
[
{
"_id": {"$oid": "507f1f77bcf86cd799439011"},
"name": "Alice",
"age": 30
},
{
"_id": {"$oid": "507f1f77bcf86cd799439012"},
"name": "Bob",
"age": 25
}
]
Common Pitfalls
Common mistakes when using mongoexport include:
- Not specifying the correct database or collection name, resulting in no data exported.
- For CSV exports, forgetting to specify
--fields, which causes an error. - Using
--outwithout write permission to the target directory. - Not using
--jsonArraywhen you want a valid JSON array output.
bash
Wrong: mongoexport --db=mydb --collection=users --type=csv --out=users.csv Right: mongoexport --db=mydb --collection=users --type=csv --fields=name,age --out=users.csv
Quick Reference
| Option | Description |
|---|---|
| --db | Specify the database name |
| --collection | Specify the collection name |
| --out | File path to save exported data |
| --jsonArray | Export data as a JSON array |
| --type | Output format: json (default) or csv |
| --fields | Comma-separated list of fields for CSV export |
Key Takeaways
Use --db and --collection to specify the source data.
Always specify --out to save the exported file.
Use --jsonArray for valid JSON array output.
For CSV exports, include --fields to list columns.
Check file permissions to avoid write errors.