|
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
|
|