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
How to get specific data in different formats with MongoDB?
MongoDB provides different formatting options to retrieve and display data from collections. You can use find() for basic queries and pretty() for formatted output display.
Syntax
// Basic query db.collection.find(query) // Formatted output db.collection.find(query).pretty() // With limit db.collection.find(query).limit(number)
Sample Data
db.getSpecificData.insertMany([
{
"StudentName": "John",
"Information": {
"FatherName": "Chris",
"Place": {
"CountryName": "US",
"ZipCode": "111344"
},
"id": "1"
}
},
{
"StudentName": "Carol",
"Information": {
"FatherName": "Robert",
"Place": {
"CountryName": "UK",
"ZipCode": "746464"
},
"id": "2"
}
},
{
"StudentName": "David",
"Information": {
"FatherName": "Carol",
"Place": {
"CountryName": "US",
"ZipCode": "567334"
},
"id": "3"
}
},
{
"StudentName": "Jace",
"Information": {
"FatherName": "Bob",
"Place": {
"CountryName": "US",
"ZipCode": "999999"
},
"id": "4"
}
}
]);
Method 1: Formatted Output with pretty()
Query to get specific data with formatted display using pretty() method ?
db.getSpecificData.find({'Information.Place.CountryName': "US"}).limit(2).pretty();
{
"_id" : ObjectId("5e039abdf5e889d7a5199509"),
"StudentName" : "John",
"Information" : {
"FatherName" : "Chris",
"Place" : {
"CountryName" : "US",
"ZipCode" : "111344"
},
"id" : "1"
}
}
{
"_id" : ObjectId("5e039ae7f5e889d7a519950b"),
"StudentName" : "David",
"Information" : {
"FatherName" : "Carol",
"Place" : {
"CountryName" : "US",
"ZipCode" : "567334"
},
"id" : "3"
}
}
Method 2: Compact Format (Default)
Query to get the same data in compact single-line format ?
db.getSpecificData.find({'Information.Place.CountryName': "US"}).limit(2);
{ "_id" : ObjectId("5e039abdf5e889d7a5199509"), "StudentName" : "John", "Information" : { "FatherName" : "Chris", "Place" : { "CountryName" : "US", "ZipCode" : "111344" }, "id" : "1" } }
{ "_id" : ObjectId("5e039ae7f5e889d7a519950b"), "StudentName" : "David", "Information" : { "FatherName" : "Carol", "Place" : { "CountryName" : "US", "ZipCode" : "567334" }, "id" : "3" } }
Key Differences
- pretty() method formats output with proper indentation and line breaks for better readability.
- Default find() displays data in compact, single-line format.
- Both methods return the same data, only the display format differs.
Conclusion
Use pretty() for human-readable formatted output and default find() for compact display. Both methods retrieve identical data but present it in different visual formats.
Advertisements
