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 ?
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