MongoDB print JSON without whitespace i.e. unpretty JSON?

MongoDBDatabaseBig Data Analytics

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++" ] }
raja
Updated on 30-Jul-2019 22:30:25

Advertisements