MongoDB Cursor
The MongoDB cursor is a pointer that references the documents of the collection returned by the find() method.
The cursor is used to access the documents. By default, the cursor iterates automatically, but can also be iterated manually by the user.
MongoDB Cursor Example
In this example, we are working with:
Database: gfg
Collection: student
Documents: Three documents contain the details of the students
Here, we use the following query to display all the documents present in the student collection
db.student.find().pretty()
This find() method returns a cursor containing all documents present in the student collection.
How to Manually Iterate a Cursor in MongoDB
There are different ways to manually iterate a cursor in MongoDB. Users can manually iterate a cursor in MongoDB by:
Assigning Cursor to a Var Keyword
In MongoDB, the find() method returns the cursor, now to access the document we need to iterate the cursor.
To iterate a cursor manually, simply assign the cursor return by the find() method to the var keyword Or JavaScript variable.
Note: In the Mongo shell, if the cursor is not assigned to a var keyword then the Mongo shell automatically iterates the cursor up to 20 documents. If a cursor is inactive for 10 min then the MongoDB server will automatically close that cursor.
Syntax:
var name = db.collection_name.find()
name
Example :
var mycursor = db.student.find({studentId:3}).pretty()
mycursor
Here, we iterate the cursor manually to find the document whose studentId is 3. So, we assigned the cursor returned by the find() method to the JavaScript variable(i.e. mycursor).
Using the next() Method
We can also use the next() cursor method to access the next document. Let us discuss with the help of an example:
Example:
var mycursor = db.student.find({studentId:{$gt:1}});
> while(mycursor.hasNext()){
... print(tojson(mycursor.next()));
... }
In this example, studentId 2 and 3 documents are displayed because, in the first line, we exclusively took the cursor to start with the studentId > 1. So it skipped 1st document and retrieved the remaining documents. Here, the print(tojson()) method is used to display the result. You can also use printjson() method to display the result.
Using the forEach() method
We can also use the forEach() method to iterate the cursor. This function applies a JavaScript function to each document from the cursor.
Syntax:
db.collection.find().forEach(<function>)
Example:
var mycursor = db.student.find({studentId:3}).pretty()
mycursor.forEach(printjson)
Here, first we store the cursor returned by the find() method(i.e., studentId:3) in the mycursor variable. Now, we use the forEach() method to iterate the cursor and display the resultant document using printjson.
Using Iterator Index
In Mongo shell, you are allowed to iterate the cursor and display the resultant document in the array using the toArray() method.
Syntax:
cursor.toArray()
Example:
var mycursor = db.student.find().pretty()
var docs = mycursor.toArray()
var resultdoc = docs[0]
resultdoc
Here, first, we assign the returned cursor to the var keyword(i.e. mycursor), in next we create an array from the resultant cursor using the toArray() method and assign the result to the var keyword(i.e. docs). Now we access the documents according to their index e.g. var resultdoc = docs[0], here we display a document whose index is 0.
Alternate Method:
You can also this method to access a document using index on the cursor.
var mycursor = db.student.find().pretty()
var resultdoc = mycursor[0]
resultdoc
MongoDB Cursor Methods
Some of the commonly used cursor methods are:
Count cursor:
In order to get the correct documents, we need to know how many documents are present for that collection. To get that we can use the count() method which returns the total number of documents present in the given collection.
Syntax:
db.collection_name.find().count()
or
db.collection_name.count()
Example:
db.student.find().count()
Here, we find the total number of documents present in the student collection using the count() method.
Cursor Limit:
The limit() method helps to fetch limited records from a collection. Suppose we have multiple documents, but we want to have the topmost or only 2 documents, then by using the limit() method, we can achieve that.
Syntax:
db.collection_name.find().limit(<number>)
Example:
db.student.find().limit(2).pretty()
Here, we only display the first two documents from the student collection.
Cursor size:
The cursor.size() method will be helpful to return a count of the number of documents that got as the output from the db.collection.find() query after applying any cursor.skip() and cursor.limit() methods. Hence, it is mentioned as it has applied cursor.skip() and cursor.limit() methods.
Syntax:
db.collection_name.find().size()
Example:
db.student.find({studentId:1}).size()
Cursor sort:
Usually while verifying documents, if the output is in sorted order, either in ascending or descending order, it will be easier. So we use the sort() method to sort the documents. If you want to sort the documents in ascending, then set the value of the field to 1 and in descending, then set -1.
Syntax:
db.collection_name.find().sort(<sort>)
Example:
db.student.find().sort({studentId:-1}).pretty()
Here, we sort all the documents present in the student collection in descending order.
Cursor.toArray():
In order to have an array that contains all documents returned by the cursor, we can use the toArray() method.
Syntax:
db.collection_name.find().toArray()
Example:
db.student.find().toArray()
Cursor.next:
The next() method is used to return the next document in a cursor. Usually, it will return the first document as that will be the result of the first document in the cursor.
Syntax:
db.student.find().next()
Example:
db.student.find().next()
Here, the next() method returns the first document from the collection.
Additional Cursor Methods in MongoDB
Cursor Methods modify the way that the underlying query is executed.
Method Name | Description |
---|---|
cursor.addOption() | This method is used to add special wire protocol flags and modify the behavior of the query. |
cursor.allowDiskUse() | This method allows MongoDB to use temporary files on disk to store data exceeding the 100-megabyte system memory limit while processing a blocking sort operation. |
cursor.allowPartialResults() | This method allows find() operation against a collection to return partial results, rather than an error if one or more queried shards are unavailable. |
cursor.batchSize() | This method is used to control the number of documents MongoDB will return to the client in a single network message. |
cursor.close() | This method is used to close a cursor and free associated server resources. |
cursor.isClosed() | This method is used to return true if the cursor is closed. |
cursor.collation() | This method is used to specify the collation for the cursor that is returned by the find() method. |
cursor.comment() | This method is used to attacha exhausts a comment to the query to allow for traceability in the logs and the system.profile collection. |
cursor.explain() | This method is used to report on the query execution plan for a cursor. |
cursor.forEach() | This function is used to apply a JavaScript function for every document present in the cursor. |
cursor.hasNext() | This method returns true if the cursor has more documents and can be iterated. |
cursor.hint() | This method forces MongoDB to use a specific index for a query. |
cursor.isExhausted() | When the cursor is closed and there are no objects remaining in the batch, this method returns true |
cursor.itcount() | cursor.count() and itcount() are both similar only. In itcount(), execution on an existing iterator, exhausting its contents in the process. |
cursor.map() | Output is available in an array by applying a function to each document in a cursor. |
cursor.max() | This method is used to specify an exclusive upper index bound for the cursor. |
cursor.maxTimeMS() | This method is used to specify the cumulative time limit in cumulative time limit in milliseconds for operations on a cursor. |
cursor.min() | This method is used to specify inclusive lower index bound for a cursor. |
cursor.next() | This method is used to retrieve the next document in a cursor. |
cursor.noCursorTimeout() | This method instructs the server to avoid closing a cursor automatically after a period of inactivity. |
cursor.objsLeftInBatch() | This method is used to find the number of documents left in the current cursor batch. |
cursor.pretty() | This method is used to display the results in an easy-to-read manner. |
cursor.readConcern() | A read concern is specified for a find() operation. |
cursor.readPref() | This method specified a read preference to a cursor to control how the client directs queries to a replica set. |
cursor.returnKey() | Usually, the find() operation resultant cursor provides documents whereas returnkey() modifies the cursor and it returns the realindex keys |
cursor.showRecordId() | This method adds an internal storage engine ID field which is returned by the cursor. |
cursor.skip() | During the display of documents, we may be required to skip few documents due to various reasons. During that time, skip() helps to display results after skipping a number of documents. |
cursor.tailable() | The method is marked as tailable with the cursors of capped collections. |
Conclusion
Cursors in MongoDB reference the documents of a collection returned by the find() method. A cursor is used to iterate over documents when the query result is returned.
In this guide on MongoDB cursors, we have covered important cursor topics like MongoDB cursor examples, cursor methods, and how to manually iterate the cursor in MongoDB.