Reputation:
I want to output the nested json array into csv.
sample.json
{
"DocId":"ABC",
"User":[
{
"Id":1234,
"Username":"sam1234",
"Name":"Sam",
"ShippingAddress":{
"Address1":"123 Main St.",
"Address2":null,
"City":"Durham",
"State":"NC"
}
},
{
"Id":5678,
"Username":"sam5678",
"Name":"Sam",
"ShippingAddress":{
"Address1":"5678 Main St.",
"Address2":null,
"City":"Durham",
"State":"NC"
}
}
]
}
enter code here
Above is the sample file, DocID must not be printed, and output in csv must be only for array contents
Id Username Name ShippingAddress
1234 sam1234 Sam 123 Main St.Durham NC
5678 sam5678 Sam 5678 Main St.Durham NC
How to print with headers, and with out headers in csv
Upvotes: 0
Views: 746
Reputation: 357
One way to do is to do it in two steps
For step 1, Lets say I have db -> test and collection -> stack, so aggregation query is:
db.stack.aggregate([
{ $unwind:"$User"},
{ $project : { Id : "$User.Id" , Username:"$User.Username", Name:"$User.Name", ShippingAddress:"$User.ShippingAddress", _id:0} },
{ $out: "result" }
])
For step 2, use mongoexport terminal utility:
mongoexport --db test --collection result --csv --fields "Id,Username,Name,ShippingAddress" --out file.csv
Upvotes: 2