Pretty printing helps you read database results easily by formatting them nicely. Cursor behavior controls how you get and move through query results step-by-step.
0
0
Pretty printing and cursor behavior in MongoDB
Introduction
When you want to see query results in a clear, easy-to-read format.
When you have many results and want to look at them one by one.
When you want to limit how many results you see at once.
When you want to save memory by not loading all results at the same time.
When you want to explore data interactively in the MongoDB shell.
Syntax
MongoDB
db.collection.find(query).pretty() // Cursor methods examples: cursor.hasNext() cursor.next() cursor.forEach(function(doc) { /* process doc */ })
pretty() formats the output for easier reading in the shell.
Cursors let you move through results one at a time or in batches.
Examples
Shows all documents in the
users collection with nice formatting.MongoDB
db.users.find().pretty()
Loops through all pending orders one by one and prints each in JSON format.
MongoDB
var cursor = db.orders.find({status: 'pending'}) while (cursor.hasNext()) { printjson(cursor.next()) }
Shows only 3 products with pretty formatting.
MongoDB
db.products.find().limit(3).pretty()Sample Program
This inserts three books into the books collection, then uses a cursor to print each book nicely formatted.
MongoDB
db.books.insertMany([
{title: 'Book A', author: 'Author 1', year: 2020},
{title: 'Book B', author: 'Author 2', year: 2019},
{title: 'Book C', author: 'Author 3', year: 2021}
])
var cursor = db.books.find()
while (cursor.hasNext()) {
printjson(cursor.next())
}OutputSuccess
Important Notes
Pretty printing only works in the MongoDB shell or compatible tools.
Cursors help manage large result sets without loading everything at once.
Use limit() to control how many results you get.
Summary
Pretty printing makes query results easier to read.
Cursors let you move through query results step-by-step.
Use cursor methods like hasNext() and next() to process data efficiently.