Search code examples
mongodbcsvmongoexport

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?


Solution

  • 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.