Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export collection to CSV in MongoDB?

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?

like image 743
Succeed Stha Avatar asked Jul 25 '11 09:07

Succeed Stha


People also ask

How do I export a collection in MongoDB?

Syntax. Run mongoexport from the system command line, not the mongo shell. You must specify the collection to export. If you do not specify an output file , mongoexport writes to the standard output (e.g. stdout).

How do I export a collection from MongoDB cloud?

Choose a file type and export location.Under Select Export File Type, select either JSON or CSV. If you select JSON, your data is exported to the target file as a comma-separated array. Then, under Output, choose where to export the file to.

How do I export a collection from MongoDB Atlas?

Just install mongo compass connect to your atlas remote DB: get the hostname like "cluster0-shard-00-00-rcapo.mongodb.net XXXXX" from your remote altas cluster then connect to the database. then you can download each document as JSON or CSV format.


1 Answers

@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:

mongoexport --host localhost --db dbname --collection name --csv --out text.csv --fields firstName,middleName,lastName 

UPDATE:

This commit: https://github.com/mongodb/mongo-tools/commit/586c00ef09c32c77907bd20d722049ed23065398 fixes the docs for 3.0.0-rc10 and later. It changes

Fields string `long:"fields" short:"f" description:"comma separated list of field names, e.g. -f name,age"` 

to

Fields string `long:"fields" short:"f" description:"comma separated list of field names (required for exporting CSV) e.g. -f \"name,age\" "` 

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:

mongoexport --host localhost --db dbname --collection name --type=csv --out text.csv --fields firstName,middleName,lastName 
like image 68
campeterson Avatar answered Sep 28 '22 08:09

campeterson