mongoexport: Usage, Options & Common CI Errors
mongoexport writes MongoDB documents out as JSON or CSV.
mongoexport produces human-readable JSON/CSV for reports and fixtures, unlike mongodump's BSON. The most common CI error is requesting CSV without naming the fields to include.
What it does
mongoexport queries a collection and writes the matching documents to JSON or CSV. It is for interchange and inspection, not full-fidelity backups (mongodump preserves types and indexes; mongoexport does not).
Common usage
mongoexport --uri="mongodb://localhost:27017/app" --collection=users --out=users.json
mongoexport --uri="mongodb://localhost:27017/app" -c users --type=csv --fields=_id,email --out=users.csv
mongoexport --uri="mongodb://localhost:27017/app" -c users --query='{"active":true}'
mongoexport --uri="mongodb://localhost:27017/app" -c users --jsonArray --out=users.jsonOptions
| Flag | What it does |
|---|---|
| -c / --collection | Collection to export |
| --type=json|csv | Output format (default json) |
| --fields <a,b> | Comma-separated fields (required for CSV) |
| --query '{...}' | Export only matching documents |
| --jsonArray | Emit one JSON array instead of one doc per line |
| --out <file> | Output file (default stdout) |
Common errors in CI
Failed: CSV mode requires a field list - CSV output needs --fields (or --fieldFile); JSON does not. By default mongoexport emits one JSON document per line (JSONL), not a JSON array - pass --jsonArray if a parser expects a single array. mongoexport drops BSON type fidelity (dates, ObjectIds become extended-JSON), so do not use it for backups that mongorestore will reload; use mongodump for that.