How to print to console an object in a MongoDB script?

To print an object to the console in a MongoDB script, you can use the printjson() method for formatted output or print() with JSON.stringify() for compact output.

Syntax

// Method 1: Formatted output
printjson({field1: "value1", field2: "value2"});

// Method 2: Compact output  
print(JSON.stringify({field1: "value1", field2: "value2"}));

Method 1: Using printjson() (Formatted Output)

The printjson() method displays objects with proper indentation and formatting ?

printjson({
    "UserId": 101,
    "UserName": "John", 
    "UserCoreSubject": ["Java", "MongoDB", "MySQL", "SQL Server"]
});
{
    "UserId" : 101,
    "UserName" : "John",
    "UserCoreSubject" : [
        "Java",
        "MongoDB", 
        "MySQL",
        "SQL Server"
    ]
}

Method 2: Using print() with JSON.stringify() (Compact Output)

For single-line compact output, use print() with JSON.stringify() ?

print(JSON.stringify({
    "UserId": 101,
    "UserName": "John",
    "UserCoreSubject": ["Java", "MongoDB", "MySQL", "SQL Server"]
}));
{"UserId":101,"UserName":"John","UserCoreSubject":["Java","MongoDB","MySQL","SQL Server"]}

Key Differences

Method Output Format Use Case
printjson() Formatted with indentation Debugging, readability
print(JSON.stringify()) Compact single line Logging, space-saving

Conclusion

Use printjson() for readable formatted output during development and debugging. Use print(JSON.stringify()) when you need compact single-line output for logging purposes.

Updated on: 2026-03-15T00:19:35+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements