How do you export all the records in a MongoDB collection to a .csv
file?
mongoexport --host localhost --db dbname --collection name --type=csv > test.csv
This asks me to specify name of the fields I need to export. Can I just export all the fields without specifying the names of fields?
I could not get mongoexport to do this for me. I found that,to get an exhaustive list of all the fields, you need to loop through the entire collection once. Use this to generate the headers. Then loop through the collection again to populate these headers for each document.
I've written a script to do just this. Converting MongoDB docs to csv irrespective of schema differences between individual documents.
https://github.com/surya-shodan/mongoexportcsv
@karoly-horvath has it right. Fields are required for csv.
According to this bug in the MongoDB issue tracker https://jira.mongodb.org/browse/SERVER-4224 you MUST provide the fields when exporting to a csv. The docs are not clear on it. That is the reason for the error.
Try this:
UPDATE:
This commit: https://github.com/mongodb/mongo-tools/commit/586c00ef09c32c77907bd20d722049ed23065398 fixes the docs for 3.0.0-rc10 and later. It changes
to
VERSION 3.0 AND ABOVE:
You should use
---type=csv
instead of--csv
since it has been deprecated.More details: https://docs.mongodb.com/manual/reference/program/mongoexport/#export-in-csv-format
Full command:
Below command used to export collection to CSV format.
Note:
naag
is database,employee1_json
is a collection.You have to manually specify it and if you think about it, it makes perfect sense. MongoDB is schemaless; CSV, on the other hand, has a fixed layout for columns. Without knowing what fields are used in different documents it's impossible to output the CSV dump.
If you have a fixed schema perhaps you could retrieve one document, harvest the field names from it with a script and pass it to mongoexport.
Also if you want to export inner json fields use dot (. operator).
JSON record:
mongoexport command with dot operator (using mongo version 3.4.7):
Output csv:
Note: Make sure you do not export an array. It would corrupt the CSV format like field userIds shown above
Also, you are not allowed spaces between comma separated field names.
BAD:
-f firstname, lastname
GOOD:
-f firstname,lastname