How do I use mongoexport to export all records in a collection to a CSV file

I am trying to export data to a CSV file but for some reason I am not getting any data in the CSV file.

I have a DB called "test", and a collection called "people". The contents of the people collection is (json export works!):

{"_id":{"$oid":"55937ce0c64ddad5023a9570"},"name":"Joe Bloggs","position":"CE"}
{"_id":{"$oid":"55937d57c64ddad5023a9571"},"name":"Jane Bloggs","position":"CE"}
{"_id":{"$oid":"55937d62c64ddad5023a9572"},"name":"Peter Smith","position":"CE"}
{"_id":{"$oid":"55937d78c64ddad5023a9573"},"name":"Sarah Smith","position":"STL"}

I am trying to export this data into a CSV file with the following command:

mongoexport --type=csv -d test -c people --fieldFile c:\dev\peopleFields.txt --out c:\dev\people.csv

When I run this command, the response is:

2015-07-01T14:56:36.787+0800   connected to: localhost
2015-07-01T14:56:36.787+0800   exported 4 records

The contents of peopleFields.txt is:

ID
Name
Position

And the resulting output to the people.csv file is:

ID,Name,Position
"","",""
"","",""
"","",""
"","",""

Could someone please explain to me what I am doing wrong?

Answers


What you are missing here is that the --fieldFile option is not a "mapping" but just a "list" of all the fields you want to export from the collection.

So to actually "match" fields present in your collection the content should be:

_id
name
position

Since the names you have do not match any fields, you get four lines ( one per document ) of blank field output, for the number of fields you specify.

The mongoexport utility itself will not "map" to alternate names. If you want different names to how they are stored in your collection then you will have to alter the output yourself.

The same goes for the output as any ObjectId value will be output as that literal string.


You can use following command to export data in csv file:

mongoexport --db dbName --collection collectionName  --type=csv --fields name,position --out fileName.csv

As per documentation,

1) The fieldFile allows you to specify fields to include in the export.

2) The file must have only one field per line, and the line(s) must end with the LF character (0x0A).

You are using different name (ID, Name, Position) in text file as that of in collection (_id, name, position)so you are getting empty fields exported.


Need Your Help

Protractor waiting for element to be in DOM

angularjs selenium protractor

I have been having some trouble using Protractor. I have a really weird ui-router state where its hard to go off of other elements to start working with the page. Is there any way to tell protracto...