0

I have a requirement to project only specific field in the json object within json array. Let's say I have a collection with many documents like below

{
 "_id" : Object("sddf3r"),
 "item_id" : "1235",
 "outerObj" : [{
    "fieldA" : "valueA",
    "fieldB" : "valueB",
    "created_at" : "2019-07-10T14:25:30.000Z"  
 }]
}

Now I want to export the fields item_id,outerObj.created_at as csv and i use the below query for it

mongoexport --host="localhost:27017" -d testdb -c items --query '{"item_id" : {$in :["1235"]}}' --csv -f item_id,outerObj.created_at --out output.csv

But this results in the whole outerObj get printed.

How should i modify the query to export only the field created_at inside the outerObj ?

Aarish Ramesh
  • 6,745
  • 15
  • 60
  • 105
  • How do you expect it to behave if there are 2 items in the "outerObj" array? – Alex Blex Aug 21 '20 at 14:06
  • @AlexBlex The inner document array is modelled in such a way that there will be only one document. jus for extensibility sake, it has been modelled as array – Aarish Ramesh Aug 21 '20 at 14:12

1 Answers1

1

If you are happy with exporting first item from outerObj array only you can use index in the field list:

mongoexport \
    --host="localhost:27017" \
    -d testdb \
    -c items \
    --query '{"item_id" : {$in :["1235"]}}' \
    --csv \
    -f item_id,outerObj.0.created_at \
    --out output.csv
Alex Blex
  • 34,704
  • 7
  • 48
  • 75