You can't directly export an "aggregate" Mongo to CSV using the mongoexport command, as it's intended for simpler data exports. However, there is a way to output the results of one such query to a new collection, which you can then export.

To do this, use $out to define the new collection's name:

db.collectionA.aggregate([ ... , {$out: "collectionB"}])

And then export it to CSV from the command line:

$ mongoexport -d databaseA -c collectionB -f field1,field2,etc --csv > results.csv

Previous on MongoDB
Mastodon Mastodon