Get output of MongoDB shell script?

You can use printjson() or print() to get output of MongoDB shell script. The printjson() method displays JavaScript objects in a formatted JSON structure, while print() outputs plain text.

Syntax

printjson(object);
print(value);

Create Sample Data

Following is the query to create an array of objects ?

var studentDetails = [
    {"StudentName": "John", "StudentAge": 21},
    {"StudentName": "Carol", "StudentAge": 24},
    {"StudentName": "David", "StudentAge": 25}
];

Example 1: Using printjson()

Following is the query to get the output of MongoDB shell script using printjson() ?

printjson(studentDetails);

This will produce the following output ?

[
    {
        "StudentName" : "John",
        "StudentAge" : 21
    },
    {
        "StudentName" : "Carol",
        "StudentAge" : 24
    },
    {
        "StudentName" : "David",
        "StudentAge" : 25
    }
]

Example 2: Using print()

You can also use print() for simple text output ?

print("Total students: " + studentDetails.length);
Total students: 3

Key Differences

  • printjson() formats output as readable JSON structure
  • print() outputs plain text or unformatted objects
  • printjson() is preferred for displaying MongoDB documents and arrays

Conclusion

Use printjson() for formatted JSON output of MongoDB objects and arrays, while print() works best for simple text messages and debugging information in shell scripts.

Updated on: 2026-03-15T00:52:14+05:30

888 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements