Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB print JSON without whitespace i.e. unpretty JSON?
To print unpretty json, use the following syntax −
var yourVariableName= db.yourCollectionName.find().sort({_id:-1}).limit(10000);
while( yourVariableName.hasNext() ) {
printjsononeline(yourVariableName.next() );
};
To understand the syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.unprettyJsonDemo.insertOne({"StudentName":"John","StudentAge":21,"StudentTechnicalSkills":["C","C++"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c900df25705caea966c557d")
}
> db.unprettyJsonDemo.insertOne({"StudentName":"Carol","StudentAge":22,"StudentTechnicalSkills":["MongoDB","MySQL"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c900e085705caea966c557e")
}
all documents from a collection with the help of find() method. The query is as follows −
> db.unprettyJsonDemo.find().pretty();
The following is the output −
{
"_id" : ObjectId("5c900df25705caea966c557d"),
"StudentName" : "John",
"StudentAge" : 21,
"StudentTechnicalSkills" : [
"C",
"C++"
]
}
{
"_id" : ObjectId("5c900e085705caea966c557e"),
"StudentName" : "Carol",
"StudentAge" : 22,
"StudentTechnicalSkills" : [
"MongoDB",
"MySQL"
]
}
Here is the query to print JSON without whitespace i.e. unpretty JSON −
> var myCursor = db.unprettyJsonDemo.find().sort({_id:-1}).limit(10000);
> while(myCursor.hasNext()){
... printjsononeline(myCursor.next());
... };
The following is the output −
{ "_id" : ObjectId("5c900e085705caea966c557e"), "StudentName" : "Carol", "StudentAge" : 22, "StudentTechnicalSkills" : [ "MongoDB", "MySQL" ] }
{ "_id" : ObjectId("5c900df25705caea966c557d"), "StudentName" : "John", "StudentAge" : 21, "StudentTechnicalSkills" : [ "C", "C++" ] }Advertisements