15

I have a MongoDB and I want to export to a .csv file.

document:

{
  "id" : 28,
  "organisation" : "Mickey Mouse company",
  "country" : "US",
  "contactpersons" : [{
      "title" : "",
      "typecontact" : "D",
      "mobilenumber" : "757784854",
      "firstname" : "Mickey",
      "lastname" : "Mouse",
      "emailaddress" : "mickey@mouse.com"
    }],
  "modifieddate" : "2013-11-21T16:04:49+0100"
}

I want to export all document and only want the field contactpersons.firstname and contactpersons.emailaddress

I use this commandline:

     mongoexport -o /tmp/export.csv -host dbmongo -port 27017 -db organisation -collection organisationa -u user -p password -csv  -fields 'contactpersons.0.firstname, contactpersons.0.emailaddress'

This works more or less, it exports but only exports the field firstname and not emailaddress. I need it also the export the field emailaddress.

Any idea how I can do this? I don't understand why it doesn't work even though I do give the emailaddress field. Do error is given.

Thanks for any help!

Steven Filipowicz
  • 389
  • 2
  • 10
  • 25
  • Double quotes worked perfectly for me anywway, mongoexport -o export.csv -db stackoverflow -collection exportcsv -fields "contactpersons.0.firstname, contactpersons.0.emailaddress" --csv – Maximiliano Rios Jan 14 '14 at 12:05

2 Answers2

12

Found it. I needed to remove the spaces.

This is wrong:

mongoexport -o /tmp/export.csv -host dbmongo -port 27017 -db organisation -collection organisationa -u user -p password -csv  -fields 'contactpersons.0.firstname, contactpersons.0.emailaddress'

This is correct:

mongoexport -o /tmp/export.csv -host dbmongo -port 27017 -db organisation -collection organisationa -u user -p password -csv  -fields 'contactpersons.0.firstname,contactpersons.0.emailaddress'
Steven Filipowicz
  • 389
  • 2
  • 10
  • 25
8

Create fields.txt file and insert the following fields into it :

contactpersons.0.firstname
contactpersons.0.emailaddress

Then you can use the following command to export given fields into .csv

mongoexport -d organisation -c organisation -fieldFile fields.txt --csv > /tmp/export.csv
Parvin Gasimzade
  • 25,180
  • 8
  • 56
  • 83
  • Need a little more info, what if I want to export multiple documents from the `contactpersons` array? For instance, I have document like this `{ "id" : 28, "organisation" : "ABC company", "country" : "US", "contactpersons" : [{ "title" : "", "firstname" : "Mickey", "lastname" : "Mouse", "emailaddress" : "mickey@mouse.com" },{ "title" : "", "firstname" : "Donald", "lastname" : "Duck", "emailaddress" : "donal@duck.com" }], "modifieddate" : "2013-11-21T16:04:49+0100" }` Need to export both the objects in the `contactpersons` array. – Ayaz Pasha Oct 15 '14 at 08:22
  • @AyazPasha Did you find any solution to export a document with an array which may content more than one element at the end? – akruspe Aug 22 '17 at 14:07