pretty() method in MongoDB :
pretty() method is used mainly to display the result in a more easy-to-read format. In this tutorial, I will show you how to use pretty() method and how the data looks with and without using pretty() and how the data looks like. The syntax of pretty() method is as below :
db.collection.find().pretty()
If we call find method in a collection, it shows all documents available in that collection. Optionally, we can pass one query to this method.
Example Usage :
Let’s try to understand this method with an example. Open your Mongo-shell and create one collection with few documents like below :
db.list.insertMany([
{_id : 1,name : "Alex",age : 16,marks : { physics : 90, chemistry : 85, mathematics : 59 }},
{_id : 2,name : "Albert",age : 17, marks : { physics : 92, chemistry : 87, mathematics : 88}},
{_id : 3,name : "Bob",age : 16, marks : { physics : 88, chemistry : 81, mathematics : 66}},
{_id : 4,name : "John",age : 17, marks : { physics : 78, chemistry : 55, mathematics : 63}}
])
It will insert these four documents to the collection list. Now, call db.list.find() to print out all documents in it. It will print the below output :
{ "_id" : 1, "name" : "Alex", "age" : 16, "marks" : { "physics" : 90, "chemistry" : 85, "mathematics"
: 59 } }
{ "_id" : 2, "name" : "Albert", "age" : 17, "marks" : { "physics" : 92, "chemistry" : 87, "mathematics
" : 88 } }
{ "_id" : 3, "name" : "Bob", "age" : 16, "marks" : { "physics" : 88, "chemistry" : 81, "mathematics" :
66 } }
{ "_id" : 4, "name" : "John", "age" : 17, "marks" : { "physics" : 78, "chemistry" : 55, "mathematics"
: 63 } }
{
"_id" : 1,
"name" : "Alex",
"age" : 16,
"marks" : {
"physics" : 90,
"chemistry" : 85,
"mathematics" : 59
}
}
{
"_id" : 2,
"name" : "Albert",
"age" : 17,
"marks" : {
"physics" : 92,
"chemistry" : 87,
"mathematics" : 88
}
}
{
"_id" : 3,
"name" : "Bob",
"age" : 16,
"marks" : {
"physics" : 88,
"chemistry" : 81,
"mathematics" : 66
}
}
{
"_id" : 4,
"name" : "John",
"age" : 17,
"marks" : {
"physics" : 78,
"chemistry" : 55,
"mathematics" : 63
}
}
{
"_id" : 1,
"name" : "Alex",
"age" : 16,
"marks" : {
"physics" : 90,
"chemistry" : 85,
"mathematics" : 59
}
}
{
"_id" : 3,
"name" : "Bob",
"age" : 16,
"marks" : {
"physics" : 88,
"chemistry" : 81,
"mathematics" : 66
}
}
Conclusion :
pretty() is useful in many cases. If our database is huge, this method really comes in handy. Go through the examples above and drop one comment below if you have any queries. You might also like :