Open In App

How to Set Pretty Print as Default in the MongoDB Shell?

In MongoDB, optimizing data readability and usability is important. Pretty print, a formatting option within MongoDB, significantly enhances the visual appeal and comprehension of query results displayed in the MongoDB shell.

In this article, We will learn about What is Pretty Print and understand some examples that help us to understand Pretty Print in-depth manner.



What is Pretty Print?

// Replace 'yourCollectionName' with the name of your MongoDB collection
db.yourCollectionName.find().pretty();

Explanation:

Let’s set up an Environment:



To understand How to Set Pretty Print as Default in the MongoDB Shell, we’re creating a collection called “prettyDemo” and inserting a document with a single field named “fieldName” and its corresponding value “fieldValue”. This helps us demonstrate the concept in detail.

Examples of How to Set Pretty Print as Default in the MongoDB Shell

Example 1

// inserting data
> db.prettyDemo.insertOne({
"ClientName": "Larry",
"ClientAge": 27,
"ClientFavoriteCountry": ["US", "UK"]
});
// data inserted
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a440de01f572ca0ccf5f2")
}
// inserting data
> db.prettyDemo.insertOne({
"ClientName": "Mike",
"ClientAge": 57,
"ClientFavoriteCountry": ["AUS", "UK"]
});
// data inserted
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8a4420e01f572ca0ccf5f3")
}

Here is the query to call pretty() function :

//show data with the help of pretty() function
>db.prettyDemo.find().pretty();

The following is the output:

Setting Pretty Print as Default

Explanation: In the above output, we Set Pretty Print as Default to the whole collection easily.

Example 2

Here, we created another collection for better understanding the concept. So, we’re creating a collection called “gfg” and inserting number of documents into the collection.

// inserting data
db.gfg.insertMany([
{
"productName": "Laptop",
"brand": "Dell",
"price": 1200
},
{
"productName": "Smartphone",
"brand": "Samsung",
"price": 800
},
{
"productName": "Headphones",
"brand": "Sony",
"price": 100
}
]);

//collection inserted
{
acknowledged: true,
insertedIds: {
'0': ObjectId('661182f9a57582b2fc0ca537'),
'1': ObjectId('661182f9a57582b2fc0ca538'),
'2': ObjectId('661182f9a57582b2fc0ca539')
}
}

Here is the query to call pretty() function :

//show data with the help of pretty() function
> db.gfg.find().pretty();

The following is the output:

Setting Pretty Print as Default

Explanation: In the above output, we Set Pretty Print as Default to the whole collection easily.

Conclusion

Overall, using pretty print as the default output format in MongoDB can improve the way you work with data. It makes query results clearer and easier to analyze, which can help to better decision-making. This simple adjustment can enhance your MongoDB experience and help you get more value from your data.

Article Tags :