15

is there a way to export only specified fields in a sub-document while using mongoexport? mongo docs says to just use -f field1, field2 etc... but that only works with top level fields. i have a document inside of the main document that also has fields. is there any way to get only those?

Example:

{
    "topField1": "topValue1",
    "topField2": "topValue2",
    "subDoc1: {
                  "subField1": "subValue1",
                  "subField2": "subValue2"
              }
}

is there a way to specify that i ONLY get the field subField2?

i know in a regular mongo query i could use "subDoc1.subField2" which would simply return {"$oid": 122432432, {"subDoc1":{"subField2": "subValue2"}} but this doesn't seem to work with mongoexport.

also i want to export as json.

bigbounty
  • 16,526
  • 5
  • 37
  • 65
Khon Lieu
  • 4,295
  • 7
  • 37
  • 39

3 Answers3

18

what kind of error do you get using dotnotation? I'm running mongoDB 1.8.2 and for me the following works:

mongoexport -d dbName -c collectionName -f subDoc1.subField2 --csv -o /path/to/file.csv

The CSV looks like this

subDoc1.subField2 #header with field names
"subValue2" #actual entry
Dimi
  • 3,521
  • 1
  • 17
  • 10
  • 1
    i don't think i was getting an error. i think the problem was it was returning unnecessary fields. but you're right it does work now! i think i was previously running mongo 1.6. now i'm running mongo 2.0.1. thanks Demi! – Khon Lieu Dec 09 '11 at 19:50
1

enter image description here

mongoexport --db db_name --collection collection_name --fields 'No,Name' --out collection_name.json

{"_id":{"$oid":"5b2a1d540e63356357cbff46"},"name":"vijil","dep":"MCA"} {"_id":{"$oid":"5b2a1d5e0e63356357cbff47"},"name":"arul","dep":"MCA"} {"_id":{"$oid":"5b2a1d670e63356357cbff48"},"name":"abessh","dep":"MCA"}

evandrix
  • 6,041
  • 4
  • 27
  • 38
vijin selvaraj
  • 124
  • 1
  • 6
  • 1
    this doesn't seem to work, still all fields are being exported – flaudre Jun 18 '18 at 10:56
  • same than yours. I tried to avoid exporting the _id field, but it seems to not be possible using json. works only if exported to csv flag. see [this post](https://stackoverflow.com/questions/12976145/mongoexport-without-id-field) – flaudre Jun 19 '18 at 09:51
-1

In case we are not sure of the subdocument value .i.e in this case : subField1 or subField2, but what we need is just to extract the first field of the sub-collection. Can mongoexport handle that ?

Chittprakash
  • 67
  • 11