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 –

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

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

Just append pretty() to the find method.

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

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

DBQuery.prototype._prettyShell = true

Apparently, findOne already prints formatted JSON –

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

Cheers!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

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

Leave a Reply

Your email address will not be published. Required fields are marked *