Is it possible to write to MongoDB console in JavaScript execution?

Yes, you can write to the MongoDB console during JavaScript execution using the print() method for strings and printjson() method for objects. These functions are built-in utilities in the MongoDB shell.

Syntax

print("yourString");
printjson(yourObjectName);

Method 1: Using print() for Strings

To display a simple string message on the console ?

print("Welcome to MongoDB Console");
Welcome to MongoDB Console

Method 2: Using printjson() for Objects

First, create a sample object ?

studentInformation = {
    "StudentName": "John",
    "StudentAge": 24,
    "StudentTechnicalSkills": ["C", "C++", "Java", "MongoDB", "MySQL"]
};

Now display the object using printjson() ?

printjson(studentInformation);
{
    "StudentName": "John",
    "StudentAge": 24,
    "StudentTechnicalSkills": [
        "C",
        "C++",
        "Java",
        "MongoDB",
        "MySQL"
    ]
}

Key Differences

  • print() - Outputs simple strings and primitive values without formatting
  • printjson() - Formats and pretty-prints JSON objects with proper indentation

Conclusion

Use print() for basic string output and printjson() for formatted object display in MongoDB shell. Both methods are essential for debugging and displaying results during JavaScript execution.

Updated on: 2026-03-15T00:12:36+05:30

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements