Prettyprint in MongoDB shell as default?

You can call pretty() function on cursor object to format MongoDB query output in a readable, indented JSON format. This is especially useful for documents with nested arrays and objects.

Syntax

db.collectionName.find().pretty();

Sample Data

Let us create a collection with sample documents ?

db.prettyDemo.insertMany([
    {
        "ClientName": "Larry",
        "ClientAge": 27,
        "ClientFavoriteCountry": ["US", "UK"]
    },
    {
        "ClientName": "Mike",
        "ClientAge": 57,
        "ClientFavoriteCountry": ["AUS", "UK"]
    }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5c8a440de01f572ca0ccf5f2"),
        ObjectId("5c8a4420e01f572ca0ccf5f3")
    ]
}

Without pretty() Function

Display all documents using the regular find() method ?

db.prettyDemo.find();
{ "_id" : ObjectId("5c8a440de01f572ca0ccf5f2"), "ClientName" : "Larry", "ClientAge" : 27, "ClientFavoriteCountry" : [ "US", "UK" ] }
{ "_id" : ObjectId("5c8a4420e01f572ca0ccf5f3"), "ClientName" : "Mike", "ClientAge" : 57, "ClientFavoriteCountry" : [ "AUS", "UK" ] }

With pretty() Function

Apply pretty() function to format the output ?

db.prettyDemo.find().pretty();
{
    "_id" : ObjectId("5c8a440de01f572ca0ccf5f2"),
    "ClientName" : "Larry",
    "ClientAge" : 27,
    "ClientFavoriteCountry" : [
        "US",
        "UK"
    ]
}
{
    "_id" : ObjectId("5c8a4420e01f572ca0ccf5f3"),
    "ClientName" : "Mike",
    "ClientAge" : 57,
    "ClientFavoriteCountry" : [
        "AUS",
        "UK"
    ]
}

Key Points

  • pretty() only affects the display format, not the actual data structure.
  • It works with any find() query including filters and projections.
  • Particularly useful for complex documents with nested arrays and objects.

Conclusion

The pretty() function formats MongoDB query output into readable, indented JSON. It's essential for analyzing complex document structures and debugging queries in the MongoDB shell.

Updated on: 2026-03-15T00:07:50+05:30

290 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements