In my current setup with mongodb 2.2.0, I am working on a way to display json data in a single line format instead of the "pretty" printing typically achieved with printjson()
or find().pretty()
. Essentially, I want the documents to be listed in json format similar to the output of db.collection.find().limit(10)
, but I want to accomplish this using a cursor in a javascript file like so:
var cursor = db.collection.find().sort({_id:-1}).limit(10000);
while(cursor.hasNext()){
//printNonPrettyJson(cursor.next()); //How???!
}
print()
is not suitable for this task as it produces undesirable output related to the object identifier.
The reason behind this requirement is that I intend to run the javascript file from the console and then direct the output to a file using the following command:
mongo mydatabase myjsfile.js >> /tmp/myoutput.txt
EDIT: The desired output format is:
> 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" }
>
as opposed to:
> 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"
}
>
This specific format is not achievable through conventional methods, hence the requirement to use a cursor object.