By default, the cursor will be iterated automatically when the result of the query is returned. But one can also explicitly go through the items returned in the cursor one by one. If you see the below example, if we have 3 documents in our collection, the cursor object will point to the first document and then iterate through all of the documents of the collection.

The following example shows how this can be done.

var myEmployee = db.Employee.find( { Employeeid : { $gt:2 }});

while(myEmployee.hasNext())

{

	print(tojson(myEmployee.next()));

}

Code Explanation:

First we take the result set of the query which finds the Employee’s whose id is greater than 2 and assign it to the JavaScript variable ‘myEmployee’ Next we use the while loop to iterate through all of the documents which are returned as part of the query. Finally for each document, we print the details of that document in JSON readable format.

If the command is executed successfully, the following Output will be shown

Output: