Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Advertisements
