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
Fetching all documents from MongoDB Collection in a beautified form
To fetch all documents from a MongoDB collection in a beautified, readable format, use the find() method combined with the pretty() method. The pretty() method formats the JSON output with proper indentation and line breaks.
Syntax
db.collectionName.find().pretty();
Create Sample Data
Let us create a collection with some sample documents ?
db.demo306.insertMany([
{"Name": "Robert", "Age": 21},
{"Name": "David", "Age": 23},
{"Name": "Mike", "Age": 25},
{"Name": "Carol", "Age": 26}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e4ea7c6f8647eb59e562038"),
ObjectId("5e4ea7cdf8647eb59e562039"),
ObjectId("5e4ea7d4f8647eb59e56203a"),
ObjectId("5e4ea7dcf8647eb59e56203b")
]
}
Example: Fetch All Documents with Pretty Format
Display all documents from the collection using find().pretty() ?
db.demo306.find().pretty();
{
"_id": ObjectId("5e4ea7c6f8647eb59e562038"),
"Name": "Robert",
"Age": 21
}
{
"_id": ObjectId("5e4ea7cdf8647eb59e562039"),
"Name": "David",
"Age": 23
}
{
"_id": ObjectId("5e4ea7d4f8647eb59e56203a"),
"Name": "Mike",
"Age": 25
}
{
"_id": ObjectId("5e4ea7dcf8647eb59e56203b"),
"Name": "Carol",
"Age": 26
}
Key Points
- Without
pretty(), documents are displayed in a single line format. - The
pretty()method only affects the display format, not the actual data. - Use
find()without parameters to retrieve all documents from a collection.
Conclusion
The find().pretty() combination provides a human-readable format for MongoDB query results. This method is essential for analyzing document structure and data during development and debugging.
Advertisements
