How to print results of script in MongoDB?

To print results of a script in MongoDB, use the printjson() method along with cursor iteration. This allows you to display query results in a formatted JSON structure, which is particularly useful when working with scripts or loops.

Syntax

var cursor = db.collection.find();
while (cursor.hasNext()) {
    printjson(cursor.next());
}

Create Sample Data

Let us first create a collection with documents ?

db.printResultScriptDemo.insertMany([
    {"StudentName": "John", "StudentAge": 21},
    {"StudentName": "Carol", "StudentAge": 20},
    {"StudentName": "David", "StudentAge": 19}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cf22c02b64a577be5a2bc0b"),
        ObjectId("5cf22c09b64a577be5a2bc0c"),
        ObjectId("5cf22c11b64a577be5a2bc0d")
    ]
}

Example: Print Script Results Using printjson()

Following is the query to print results of script using cursor iteration ?

var document = db.printResultScriptDemo.find();
while (document.hasNext()) {
    printjson(document.next());
}
{
    "_id": ObjectId("5cf22c02b64a577be5a2bc0b"),
    "StudentName": "John",
    "StudentAge": 21
}
{
    "_id": ObjectId("5cf22c09b64a577be5a2bc0c"),
    "StudentName": "Carol",
    "StudentAge": 20
}
{
    "_id": ObjectId("5cf22c11b64a577be5a2bc0d"),
    "StudentName": "David",
    "StudentAge": 19
}

Key Points

  • printjson() formats output with proper indentation and line breaks
  • hasNext() checks if more documents exist in the cursor
  • next() retrieves the next document from the cursor

Conclusion

Use printjson() with cursor iteration to display formatted script results in MongoDB. This method provides clean, readable output for each document in your query results.

Updated on: 2026-03-15T01:29:08+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements