Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mongoexport attributes from an array of objects to CSV?

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?

like image 558
kgarske Avatar asked May 05 '12 21:05

kgarske


People also ask

How do I export a MongoDB collection to CSV?

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.

How do I export data from MongoDB Atlas?

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.


1 Answers

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,

like image 102
arober11 Avatar answered Sep 20 '22 11:09

arober11