[SERVER-24839] toCSV() functionality Created: 29/Jun/16  Updated: 14/Jul/16  Resolved: 30/Jun/16

Status: Closed
Project: Core Server
Component/s: Shell
Affects Version/s: None
Fix Version/s: None

Type: New Feature Priority: Minor - P4
Reporter: Richard Penner Assignee: Ramon Fernandez Marina
Resolution: Won't Fix Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Participants:

 Description   

Almost all of my queries take the form

db.mycollection.find(

{…}

).toArray().forEach(function(o)

{print(o._id+"\t"+o.total);}

)

i.e. I don't want JSON output, I want CSV output because I'm copying and pasting into Excel.



 Comments   
Comment by Ramon Fernandez Marina [ 30/Jun/16 ]

richardpenner, tabular formats like CSV/TSV don't really play nicely with the schema-free/nested nature of documents, so a toCSV() method is not a good candidate for inclusion as standard in the shell.

The good news is that you can use the mongorc.js to create this functionality yourself. My colleague kevin.pulo sent the example below, which you can enhance to meet your specific needs:

DBQuery.prototype.toCSV = function () {
	var fields = Array.prototype.slice.call(arguments);
	assert.gte(fields.length, 1, "pass at least one field name");
	print(fields.join(","));
	return this.forEach(function (doc) {
		var values = fields.map(function (field) {
			return tojson(doc[field]);
		});
		print(values.join(","));
	});
}

> db.foo.find()
{ "_id" : ObjectId("574e91f30321b72259384e1d") }
{ "_id" : ObjectId("5774cce6b8b0357c351b545a"), "a" : 1 }
{ "_id" : ObjectId("5774cce8b8b0357c351b545b"), "b" : 1 }
{ "_id" : ObjectId("5774ccedb8b0357c351b545c"), "c" : 1, "a" : 1 }
> db.foo.find().toCSV("_id","a","c")
_id,a,c
ObjectId("574e91f30321b72259384e1d"),undefined,undefined
ObjectId("5774cce6b8b0357c351b545a"),1,undefined
ObjectId("5774cce8b8b0357c351b545b"),undefined,undefined
ObjectId("5774ccedb8b0357c351b545c"),1,1
> db.foo.find().toCSV("a","b","c")
a,b,c
undefined,undefined,undefined
1,undefined,undefined
undefined,1,undefined
1,undefined,1
> db.foo.find().toCSV()
assert: 0 is not greater than or eq 1 : pass at least one field name
doassert@src/mongo/shell/assert.js:15:14
assert.gte@src/mongo/shell/assert.js:335:5
DBQuery.prototype.toCSV@(shell):3:1
@(shell):1:1
 
2016-06-30T18:00:23.565+1000 E QUERY    [thread1] Error: 0 is not greater than or eq 1 : pass at least one field name :
doassert@src/mongo/shell/assert.js:15:14
assert.gte@src/mongo/shell/assert.js:335:5
DBQuery.prototype.toCSV@(shell):3:1
@(shell):1:1

Generated at Thu Feb 08 04:07:33 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.