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
How to loop through collections with a cursor in MongoDB?
In MongoDB, you can loop through collections with a cursor using the while loop with hasNext() and next() methods. A cursor is returned by the find() method and allows you to iterate through documents one by one.
Syntax
var cursor = db.collectionName.find();
while(cursor.hasNext()) {
var document = cursor.next();
printjson(document);
}
Create Sample Data
Let us create a collection with student documents ?
db.loopThroughCollectionDemo.insertMany([
{"StudentName": "John", "StudentAge": 23},
{"StudentName": "Larry", "StudentAge": 21},
{"StudentName": "Chris", "StudentAge": 25},
{"StudentName": "Robert", "StudentAge": 24}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9ca81f2d6669774125247f"),
ObjectId("5c9ca8272d66697741252480"),
ObjectId("5c9ca8462d66697741252481"),
ObjectId("5c9ca8632d66697741252482")
]
}
Verify Sample Data
db.loopThroughCollectionDemo.find().pretty();
{
"_id": ObjectId("5c9ca81f2d6669774125247f"),
"StudentName": "John",
"StudentAge": 23
}
{
"_id": ObjectId("5c9ca8272d66697741252480"),
"StudentName": "Larry",
"StudentAge": 21
}
{
"_id": ObjectId("5c9ca8462d66697741252481"),
"StudentName": "Chris",
"StudentAge": 25
}
{
"_id": ObjectId("5c9ca8632d66697741252482"),
"StudentName": "Robert",
"StudentAge": 24
}
Example: Loop Through Collection with Cursor
Use a while loop to iterate through all documents ?
var allDocumentValue;
var cursor = db.loopThroughCollectionDemo.find();
while(cursor.hasNext()) {
allDocumentValue = cursor.next();
printjson(allDocumentValue);
}
{
"_id": ObjectId("5c9ca81f2d6669774125247f"),
"StudentName": "John",
"StudentAge": 23
}
{
"_id": ObjectId("5c9ca8272d66697741252480"),
"StudentName": "Larry",
"StudentAge": 21
}
{
"_id": ObjectId("5c9ca8462d66697741252481"),
"StudentName": "Chris",
"StudentAge": 25
}
{
"_id": ObjectId("5c9ca8632d66697741252482"),
"StudentName": "Robert",
"StudentAge": 24
}
Key Points
-
Cursor − Returned by
find()method for iterating through documents -
hasNext() − Returns
trueif more documents exist in the cursor - next() − Returns the next document and advances the cursor
- printjson() − Formats and displays the document in readable JSON
Conclusion
MongoDB cursors provide an efficient way to loop through large collections. Use hasNext() and next() methods with a while loop to process documents individually without loading all data into memory at once.
Advertisements
