I need to export values of objects in an array to CSV. Let's say my document is:
{ name:"test", types:[ {type:"A"}, {type:"B"}, {type:"C"} ] }
My goal is to produce output like:
"test", "A" "test", "B" "test", "C"
The following would also be acceptable:
"test", "A,B,C"
I'm trying to accomplish this via mongoexport using:
mongoexport -h localhost -d mydb -c mycollection -f name,types.type --csv
Unfortunately, I'm getting:
"test",
I've found documentation on referencing specific array elements, like "types.0.type", but the length of my array is unknown. Any ideas?
Export MongoDB to CSV (e.g. Excel) Open the Export Wizard and select your export source. This screen only appears if you haven't chosen an item in the Connection Tree, run a previous query, or selected specific documents. Next, choose CSV as the export format then click Next.
So, to export data from the MongoDB database, MongoDB provides a command-line tool known as mongoexport. Using this tool you can exports data of a collection in JSON or CSV(comma-separated value) format.
If your happy with Perl then the ARJsonLib.pm library in the following article, provides the majority of functionality you'll need, to create your own little toy. Note the version in the article is a stub from a toy I hacked together that does exactly what you want along with some other stuff, but as not a mongoDB article it's lacking one function you'll need, that finds the fields/keys in a mongoDB collection, and stores them in an array, but trivial to reconstruct, just write yourself something that pull's n documents from your collection, pushes them into an array and calls findKeysInJsonColl(). Anyway a couple of the functions will take a MongoDB cursor as parameter, and:
convertToDojoGrid()
convertToExcel()
Again the CSV output is missing, but trivial to add back to convertToExcel().
e.g.
...
my $iRows = convertToExcel("/tmp/test.xlsx", $oMongoData, "", \@aOutFields, "xlsx");
...
Where: $oMongoData is a MongoDB Cursor reference and @aOutFields an array containing the fields/keys you wish to appear in the sheet,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With