Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb print json without whitespace i.e. unpretty json

I'm using mongodb 2.2.0 and am trying to print json in a single line as opposed to "pretty" printing using printjson() or find().pretty(). i.e. I need the documents listed in json format as done by just running the command db.collection.find().limit(10), but I need it done using a cursor in a javascript file as follows:

var cursor = db.collection.find().sort({_id:-1}).limit(10000); while(cursor.hasNext()){     //printNonPrettyJson(cursor.next()); //How???! } 

print() doesn't do the job, it just prints some gibberish about the object identifier.

The reason I want this is because I'm calling the javascript file from the console and then passing the output to a file as follows:

mongo mydatabase myjsfile.js >> /tmp/myoutput.txt 

EDIT: I want the output as follows:

> db.zips.find().limit(2) { "city" : "ACMAR", "loc" : [ -86.51557, 33.584132 ], "pop" : 6055, "state" : "A L", "_id" : "35004" } { "city" : "ADAMSVILLE", "loc" : [ -86.959727, 33.588437 ], "pop" : 10616, "stat e" : "AL", "_id" : "35005" } > 

and not like:

> db.zips.find().limit(2).pretty() {         "city" : "ACMAR",         "loc" : [                 -86.51557,                 33.584132         ],         "pop" : 6055,         "state" : "AL",         "_id" : "35004" } {         "city" : "ADAMSVILLE",         "loc" : [                 -86.959727,                 33.588437         ],         "pop" : 10616,         "state" : "AL",         "_id" : "35005" } > 

as is given by all the other methods. Again, I need this using a cursor object.

like image 899
Plasty Grove Avatar asked Feb 07 '13 13:02

Plasty Grove


1 Answers

var cursor = db.collection.find().sort({_id:-1}).limit(10000); while(cursor.hasNext()){     printjsononeline(cursor.next()); } 
like image 140
MaratC Avatar answered Sep 28 '22 09:09

MaratC