0
0
MongoDBquery~30 mins

Pretty printing and cursor behavior in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Pretty Printing and Cursor Behavior in MongoDB
📖 Scenario: You are managing a small library database using MongoDB. You want to list all books in a readable format and understand how to work with the cursor that MongoDB returns when you query the collection.
🎯 Goal: Learn how to pretty print query results in MongoDB shell and how to use the cursor to iterate over documents.
📋 What You'll Learn
Create a collection called books with specific documents
Use a variable to hold the cursor returned by a query
Use the pretty() method to display documents in a readable format
Use the cursor's hasNext() and next() methods to iterate documents
💡 Why This Matters
🌍 Real World
Managing and querying collections in MongoDB is common in web applications, content management, and data analysis.
💼 Career
Understanding cursor behavior and pretty printing helps developers and database administrators efficiently retrieve and display data.
Progress0 / 4 steps
1
Create the books collection with sample documents
Insert three documents into the books collection with these exact fields and values: { title: "The Hobbit", author: "J.R.R. Tolkien", year: 1937 }, { title: "1984", author: "George Orwell", year: 1949 }, and { title: "To Kill a Mockingbird", author: "Harper Lee", year: 1960 }.
MongoDB
Need a hint?

Use db.books.insertMany() with an array of objects for the three books.

2
Assign the query result to a cursor variable
Create a variable called cursor and assign it the result of db.books.find() to get all documents from the books collection.
MongoDB
Need a hint?

Use var cursor = db.books.find() to store the cursor.

3
Use pretty() to display documents nicely
Call the pretty() method on the cursor variable to display all documents in a readable format.
MongoDB
Need a hint?

Call pretty() on the cursor variable like cursor.pretty().

4
Iterate over the cursor using hasNext() and next()
Write a while loop that uses cursor.hasNext() to check if there are more documents, and inside the loop call cursor.next() to get each document.
MongoDB
Need a hint?

Use while (cursor.hasNext()) { cursor.next() } to loop through all documents.