MongoDB Pretty Print Result Objects in Mongo Interactive Shell

This is just a mongodb quick tip in regards to printing the result sets with proper formatting in the mongo interactive shell.

Usually when you select documents in a collection using find() in the console, this is how the results are dumped –

[bash]
> db.task.find()
{ "__v" : 0, "_id" : ObjectId("515e5ddf2605cb6e15000001"), "created_at" : ISODate("2013-04-05T05:15:11.393Z"), "created_by" : ObjectId("5155c1870cee62ee48000001"), "description" : "need food", "latitude" : 22.572646, "loc" : { "type" : "Point", "coordinates" : [ 88.36389500000001, 22.572646 ] }, "longitude" : 88.36389500000001, "runner_id" : ObjectId("515552ce3954197235000002"), "status" : "closed", "status_at" : ISODate("2013-04-05T05:18:16.988Z"), "tag" : "food_pickup", "token" : "meiaa" }
[/bash]

Just append pretty() to the find method.

[bash]
> db.task.find().pretty()
{
"__v" : 0,
"_id" : ObjectId("515e5ddf2605cb6e15000001"),
"created_at" : ISODate("2013-04-05T05:15:11.393Z"),
"created_by" : ObjectId("5155c1870cee62ee48000001"),
"description" : "need food",
"latitude" : 22.572646,
"loc" : {
"type" : "Point",
"coordinates" : [
88.36389500000001,
22.572646
]
},
"longitude" : 88.36389500000001,
"runner_id" : ObjectId("515552ce3954197235000002"),
"status" : "closed",
"status_at" : ISODate("2013-04-05T05:18:16.988Z"),
"tag" : "food_pickup",
"token" : "meiaa"
}
[/bash]

You may also add this config line to ~/.mongorc.js to enable pretty printing by default.

[text]
DBQuery.prototype._prettyShell = true
[/text]

Apparently, findOne already prints formatted JSON –

[bash]
> db.task.findOne()
{
"__v" : 0,
"_id" : ObjectId("515e5ddf2605cb6e15000001"),
"created_at" : ISODate("2013-04-05T05:15:11.393Z"),
"created_by" : ObjectId("5155c1870cee62ee48000001"),
"description" : "need lol",
"latitude" : 22.572646,
"loc" : {
"type" : "Point",
"coordinates" : [
88.36389500000001,
22.572646
]
},
"longitude" : 88.36389500000001,
"runner_id" : ObjectId("515552ce3954197235000002"),
"status" : "closed",
"status_at" : ISODate("2013-04-05T05:18:16.988Z"),
"tag" : "food_pickup",
"token" : "meiaa"
}
[/bash]

Cheers!

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.