Introduction to MongoDB cursor.tryNext() Method

MongoDB is a non-relational database, and in MongoDB, cursor.tryNext() is a method used to retrieve the next document in a cursor. If there is a document available, it returns the document, otherwise it returns null.

Syntax

The syntax for the cursor.tryNext() method is as follows:

db.collection.find().tryNext()

Use Cases

The cursor.tryNext() method is typically used to iterate over a result set to retrieve documents and perform some operation such as updating or deleting documents. Unlike the cursor.next() method, the tryNext() method does not throw an exception when there are no more available documents, but instead returns null.

Examples

Assuming there is a collection named user containing the following documents:

{ "_id" : ObjectId("60f52773a9b6799bfe852e12"), "name" : "Alice", "age" : 25 }
{ "_id" : ObjectId("60f5277ca9b6799bfe852e13"), "name" : "Bob", "age" : 30 }
{ "_id" : ObjectId("60f52786a9b6799bfe852e14"), "name" : "Charlie", "age" : 35 }

We can now use the following code to iterate through the documents and print the name and age fields for each document:

cursor = db.user.find()
while doc := cursor.tryNext():
    print(doc['name'], doc['age'])

The output will be:

Alice 25
Bob 30
Charlie 35

If we try to continue iterating over the result set, the cursor.tryNext() method will return null and exit the loop:

while doc := cursor.tryNext():
    print(doc['name'], doc['age'])
print('Done')

The output will be:

Done

Conclusion

The cursor.tryNext() method is a very useful method of the MongoDB cursor object that helps us to iterate over a result set and retrieve documents without throwing an exception when there are no more available documents. Unlike the cursor.next() method, the tryNext() method returns null when there are no more available documents.