How to get values of cursor in MongoDB?

To get values of cursor in MongoDB, use the hasNext() method to iterate through cursor results. A cursor is returned by query operations like find() and allows you to process documents one by one.

Syntax

var cursor = db.collection.find(query);
while (cursor.hasNext()) {
    print(tojson(cursor.next()));
}

Sample Data

db.demo191.insertMany([
    {"EmployeeId": 1, "EmployeeName": "Chris Brown"},
    {"EmployeeId": 2, "EmployeeName": "David Miller"},
    {"EmployeeId": 1, "EmployeeName": "John Doe"},
    {"EmployeeId": 1, "EmployeeName": "John Smith"}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e3ad95303d395bdc21346c5"),
        ObjectId("5e3ad95f03d395bdc21346c6"),
        ObjectId("5e3ad96803d395bdc21346c7"),
        ObjectId("5e3ad97003d395bdc21346c8")
    ]
}

Display all documents from the collection ?

db.demo191.find();
{ "_id": ObjectId("5e3ad95303d395bdc21346c5"), "EmployeeId": 1, "EmployeeName": "Chris Brown" }
{ "_id": ObjectId("5e3ad95f03d395bdc21346c6"), "EmployeeId": 2, "EmployeeName": "David Miller" }
{ "_id": ObjectId("5e3ad96803d395bdc21346c7"), "EmployeeId": 1, "EmployeeName": "John Doe" }
{ "_id": ObjectId("5e3ad97003d395bdc21346c8"), "EmployeeId": 1, "EmployeeName": "John Smith" }

Example: Iterating Through Cursor Values

Get values of cursor object for employees with EmployeeId 1 ?

var cursor = db.demo191.find({"EmployeeId": 1});
while (cursor.hasNext()) {
    print(tojson(cursor.next()));
}
{
    "_id": ObjectId("5e3ad95303d395bdc21346c5"),
    "EmployeeId": 1,
    "EmployeeName": "Chris Brown"
}
{
    "_id": ObjectId("5e3ad96803d395bdc21346c7"),
    "EmployeeId": 1,
    "EmployeeName": "John Doe"
}
{
    "_id": ObjectId("5e3ad97003d395bdc21346c8"),
    "EmployeeId": 1,
    "EmployeeName": "John Smith"
}

Key Points

  • hasNext() returns true if more documents are available in the cursor
  • next() retrieves the next document and advances the cursor position
  • tojson() formats the document output in readable JSON format

Conclusion

Use hasNext() and next() methods to iterate through cursor values in MongoDB. This approach provides efficient document-by-document processing for query results.

Updated on: 2026-03-15T01:41:59+05:30

727 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements