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
Is there any way to see the MongoDB results in a better format?
Yes, MongoDB provides several methods to display query results in a better, more readable format instead of the default single-line output. The most common approaches are findOne() and find().toArray().
Syntax
// Display single document in formatted JSON db.collection.findOne(); // Display all documents in formatted JSON array db.collection.find().toArray();
Sample Data
Let us first create a collection with sample documents ?
db.betterFormatDemo.insertMany([
{"StudentName": "Adam Smith", "StudentScores": [98, 67, 89]},
{"StudentName": "John Doe", "StudentScores": [67, 89, 56]},
{"StudentName": "Sam Williams", "StudentScores": [45, 43, 33]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd7ab826d78f205348bc640"),
ObjectId("5cd7ab936d78f205348bc641"),
ObjectId("5cd7aba76d78f205348bc642")
]
}
The default find() method displays results in a single line format ?
db.betterFormatDemo.find();
{ "_id": ObjectId("5cd7ab826d78f205348bc640"), "StudentName": "Adam Smith", "StudentScores": [98, 67, 89] }
{ "_id": ObjectId("5cd7ab936d78f205348bc641"), "StudentName": "John Doe", "StudentScores": [67, 89, 56] }
{ "_id": ObjectId("5cd7aba76d78f205348bc642"), "StudentName": "Sam Williams", "StudentScores": [45, 43, 33] }
Method 1: Using findOne()
The findOne() method returns only the first document in a formatted JSON structure ?
db.betterFormatDemo.findOne();
{
"_id": ObjectId("5cd7ab826d78f205348bc640"),
"StudentName": "Adam Smith",
"StudentScores": [
98,
67,
89
]
}
Method 2: Using find().toArray()
The find().toArray() method returns all matching documents in a formatted JSON array ?
db.betterFormatDemo.find().toArray();
[
{
"_id": ObjectId("5cd7ab826d78f205348bc640"),
"StudentName": "Adam Smith",
"StudentScores": [
98,
67,
89
]
},
{
"_id": ObjectId("5cd7ab936d78f205348bc641"),
"StudentName": "John Doe",
"StudentScores": [
67,
89,
56
]
},
{
"_id": ObjectId("5cd7aba76d78f205348bc642"),
"StudentName": "Sam Williams",
"StudentScores": [
45,
43,
33
]
}
]
Key Differences
-
findOne()returns single document with proper JSON formatting -
find().toArray()returns all documents as a formatted JSON array - Both methods provide better readability compared to the default cursor output
Conclusion
Use findOne() for formatted single document output and find().toArray() for formatted multi-document results. Both methods significantly improve readability over the default cursor display format.
Advertisements
