• Home
  • Testing
  • SAP
  • Web
  • Must Learn!
  • Big Data
  • Live Projects
  • Blog

When the db.collection.find () function is used to search for documents in the collection, the result returns a pointer to the collection of documents returned which is called a cursor.

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 will point to the first document and then iterate through all of the documents of the collection.

MongoDB cursor

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:

  1. 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'
  2. Next we use the while loop to iterate through all of the documents which are returned as part of the query.
  3. 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:

MongoDB cursor

 

YOU MIGHT LIKE: