Mongodb export nested field

14.1k Views Asked by At

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" : "[email protected]"
    }],
  "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!

2

There are 2 best solutions below

1
On

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'
2
On

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