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

To print JSON without whitespace (unpretty JSON) in MongoDB, use the printjsononeline() function to compress documents into single-line format without pretty-print formatting.

Syntax

var cursor = db.collection.find().sort({_id:-1}).limit(10000);
while(cursor.hasNext()) {
    printjsononeline(cursor.next());
}

Sample Data

db.unprettyJsonDemo.insertMany([
    {"StudentName":"John","StudentAge":21,"StudentTechnicalSkills":["C","C++"]},
    {"StudentName":"Carol","StudentAge":22,"StudentTechnicalSkills":["MongoDB","MySQL"]}
]);
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5c900df25705caea966c557d"),
        ObjectId("5c900e085705caea966c557e")
    ]
}

Example: Display Pretty JSON (Default Format)

db.unprettyJsonDemo.find().pretty();
{
    "_id" : ObjectId("5c900df25705caea966c557d"),
    "StudentName" : "John",
    "StudentAge" : 21,
    "StudentTechnicalSkills" : [
        "C",
        "C++"
    ]
}
{
    "_id" : ObjectId("5c900e085705caea966c557e"),
    "StudentName" : "Carol",
    "StudentAge" : 22,
    "StudentTechnicalSkills" : [
        "MongoDB",
        "MySQL"
    ]
}

Example: Print Unpretty JSON (Single Line)

var myCursor = db.unprettyJsonDemo.find().sort({_id:-1}).limit(10000);
while(myCursor.hasNext()) {
    printjsononeline(myCursor.next());
}
{ "_id" : ObjectId("5c900e085705caea966c557e"), "StudentName" : "Carol", "StudentAge" : 22, "StudentTechnicalSkills" : [ "MongoDB", "MySQL" ] }
{ "_id" : ObjectId("5c900df25705caea966c557d"), "StudentName" : "John", "StudentAge" : 21, "StudentTechnicalSkills" : [ "C", "C++" ] }

Conclusion

The printjsononeline() function removes all formatting and whitespace, displaying MongoDB documents as compact single-line JSON. This is useful for logging or when you need compressed output without pretty-print formatting.

Updated on: 2026-03-15T00:16:24+05:30

726 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements