Loading

Mongo DB

What is Cursor in MongoDB?. The Complete Mongo DB Developer Course 2023 [Videos].

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 object 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 Employees 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

See All

Comments (196 Comments)

Submit Your Comment

See All Posts

Related Posts

Mongo DB / Youtube

What is MongoDB and why use it?

MongoDB is an open source NoSQL database management program. NoSQL is used as an alternative to traditional relational databases. NoSQL databases are quite useful for working with large sets of distributed data. MongoDB is a tool that can manage document-oriented information, store or retrieve information.
27-dec-2020 /4 /196

Mongo DB / Youtube

What is the difference between a document and a collection in MongoDB?

Databases, collections, documents are important parts of MongoDB without them you are not able to store data on the MongoDB server. A Database contains a collection, and a collection contains documents and the documents contain data, they are related to each other.
27-jan-2021 /4 /196

Mongo DB / Youtube

What is MongoDB and why use it?

MongoDB is an open source NoSQL database management program. NoSQL is used as an alternative to traditional relational databases. NoSQL databases are quite useful for working with large sets of distributed data. MongoDB is a tool that can manage document-oriented information, store or retrieve information.
24-May-2021 /4 /196