The script that you're using is monkey-patching DBCommandCursor.prototype.toCsv
to add the toCsv
method to cursors, and it seems like that doesn't work for aggregation cursors for some reason (and doesn't work at all on the version of mongo I'm running).
Rather than figuring out why the mongo shell isn't behaving the way that you'd like, one dangerous approach would be to instead monkey-patch the Array.prototype
Array.prototype.toCSV = function toMediocreCSV () {
const results = this;
const headers = {};
results.forEach((result) =>
Object.keys(result).forEach((key) => headers[key] = true)
)
const keys = Object.keys(headers);
print(keys.join(","));
results.forEach((result) =>
print(keys.map((key) => result[key] != null ? result[key] : '')
.join(","))
)
}
> db.test.aggregate().toArray().toCSV()
_id,a,b,c
ObjectId("5d1a77e1688b8f1d66098375"),1,2,
ObjectId("5d1a77e1688b8f1d66098376"),3,,4
Alternatively, you could write a similar function that takes in an array and formats it the way that you'd like: the only benefit to modifying the prototype would be the ability to chain things nicely.