Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Iterate a cursor and print a document in MongoDB?
To iterate a cursor and print documents in MongoDB, use the forEach() method with printjson. This approach allows you to process each document individually and format the output for better readability.
Syntax
db.collection.find().forEach(printjson);
Create Sample Data
Let's create a collection with student documents ?
db.cursorDemo.insertMany([
{"StudentFullName": "John Smith", "StudentAge": 23},
{"StudentFullName": "John Doe", "StudentAge": 21},
{"StudentFullName": "Carol Taylor", "StudentAge": 20},
{"StudentFullName": "Chris Brown", "StudentAge": 24}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cc7f0d08f9e6ff3eb0ce442"),
ObjectId("5cc7f0df8f9e6ff3eb0ce443"),
ObjectId("5cc7f0eb8f9e6ff3eb0ce444"),
ObjectId("5cc7f0f88f9e6ff3eb0ce445")
]
}
Method 1: Using forEach() with printjson
Iterate through all documents and print them using printjson ?
db.cursorDemo.find().forEach(printjson);
{
"_id": ObjectId("5cc7f0d08f9e6ff3eb0ce442"),
"StudentFullName": "John Smith",
"StudentAge": 23
}
{
"_id": ObjectId("5cc7f0df8f9e6ff3eb0ce443"),
"StudentFullName": "John Doe",
"StudentAge": 21
}
{
"_id": ObjectId("5cc7f0eb8f9e6ff3eb0ce444"),
"StudentFullName": "Carol Taylor",
"StudentAge": 20
}
{
"_id": ObjectId("5cc7f0f88f9e6ff3eb0ce445"),
"StudentFullName": "Chris Brown",
"StudentAge": 24
}
Method 2: Using Projection with forEach()
Display only specific fields like "StudentFullName" and "StudentAge" (excluding _id) ?
db.cursorDemo.find({}, {"StudentFullName": 1, "StudentAge": 1, "_id": 0}).forEach(printjson);
{"StudentFullName": "John Smith", "StudentAge": 23}
{"StudentFullName": "John Doe", "StudentAge": 21}
{"StudentFullName": "Carol Taylor", "StudentAge": 20}
{"StudentFullName": "Chris Brown", "StudentAge": 24}
Key Points
-
forEach(printjson)processes each document individually with proper JSON formatting. - Use projection (
{"field": 1, "_id": 0}) to display only specific fields. -
printjsonautomatically formats the output for better readability.
Conclusion
The forEach(printjson) method provides an efficient way to iterate through MongoDB cursors and print formatted documents. Combine it with projection to display only the required fields.
Advertisements
