DBWeinstein
DBWeinstein

Reputation: 9489

How to export mongoDB data into a CSV format?

I'm looking for a very simple way to export data from mongoDB into a CSV. Most of the answers involve bash scripts… etc. Is there a simple mongoDB command that will just export the data into CSV?

Upvotes: 20

Views: 50512

Answers (4)

viveknaskar
viveknaskar

Reputation: 2205

Although, the above answers are correct, but it won't work until you add the --out parameter where you specify your csv file.

The command would be:

mongoexport --db users --collection contacts --type=csv --fieldFile fields.txt --out=contacts_output.csv

where,

--out=<output_file_name> or -o=<output_file_name> should be used to specify the output file that you want to export to.

Upvotes: 2

Jay Dangar
Jay Dangar

Reputation: 3469

It's pretty easy with mongoDB compass, you just need to goto

Collection -> Export Collection -> Select Export data as JSON or CSV

and export the data.

Upvotes: 1

andyb
andyb

Reputation: 43823

Update:

As of mongo 3.0.6 --csv is no longer supported and the new flag is --type=csv, so the command would be

mongoexport --db users --collection contacts --type=csv --fieldFile fields.txt

Original answer:

This can be done from the command line using the mongo utility function mongoexport --csv.

Alongside the --csv the documentation states that you also need to use --fields or specify a file with the fields in using --fieldFile.

Have a look at the usage examples and see if they help, for example:

mongoexport --db users --collection contacts --csv --fieldFile fields.txt

Upvotes: 27

Fabio Espinosa
Fabio Espinosa

Reputation: 1002

If you already have the .bson file, in order to export to csv:

bsondump collection.bson > file.csv

Upvotes: 8

Related Questions