The Wayback Machine - https://web.archive.org/web/20240927192831/https://www.geeksforgeeks.org/mongodb-cursor/
Open In App

MongoDB Cursor

Last Updated : 18 Apr, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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).

manually iterate a cursor in mongodb

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.

next() cursor method example

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.

foreach() method example

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.

toArray() method example

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

access a document using index on the cursor

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.

count cursor

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 limit

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 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 sort

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.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.

cursor.next()

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.



Previous Article
Next Article

Similar Reads

Alternatives to MongoDB cursor.toArray() in NodeJS
MongoDB's cursor.toArray() method is used to fetch all documents from a cursor into an array in Node.js applications. However, there are some cases where alternative methods might be more suitable, such as when dealing with large datasets with more control over the data retrieval process. In this article, we will discuss some alternatives to MongoD
3 min read
Connect MongoDB (AWS) from Local Machine using WinSCP and MongoDB Compass
Pre-requisite: AWS and MongoDB In this article, we are going to connect to the Mongo database of the AWS Ubuntu Server instance using WinSCP and learn how to get connected to the server from your local machine using MongoDB Compass.  If you haven't installed a MongoDB server in your AWS EC2 instance then follow the steps present in this article and
4 min read
MongoDB - Delete Multiple Documents Using MongoDB Shell
The db.collection.deleteMany() method is used to delete multiple documents from a collection in Mongo Shell. This method deletes multiple documents from the collection according to the filter. The deleteMany() is a Mongo shell method, which can delete multiple documents. This method can be used in multi-document transactions. If you use this method
2 min read
Connect MongoDB Atlas Cluster to MongoDB Compass
MongoDB Compass is a free GUI for MongoDB. You might want to connect MongoDB Atlas Cluster to MongoDB Compass to take benefit of the GUI model for database administration. This guide explains how to connect MongoDB Atlas Cluster to MongoDB Compass. The connection process involves obtaining a connection string from MongoDB Atlas, configuring MongoDB
4 min read
MongoDB Shell vs MongoDB Node.JS Driver
MongoDB Shell and the MongoDB Node.js Driver are both tools for interacting with MongoDB, but they serve different purposes and are used in different contexts. Here's a comparison of the two: MongoDB Node.JS DriverA Node.js package called the MongoDB Node.js Driver enables programmatic communication between applications and MongoDB databases. Throu
4 min read
MongoDB Compass vs MongoDB Atlas
MongoDB is a popular NoSQL database known for flexibility and scalability. MongoDB Compass offers a graphical interface for managing databases visually while MongoDB Atlas is a cloud-based service for automated management and scaling of MongoDB databases. In this article, We will learn about the in-depth understanding of the difference between the
5 min read
Mongoose Aggregate.prototype.cursor() API
The Aggregate API.prototype.cursor() method of the Mongoose API is used to perform aggregation tasks. It allows us to iterate the result set. Aggregation cursor object allows us to perform iteration task on each document object in result set one by one. Syntax: aggregate(...).cursor( options ) Parameters: This method accepts a single parameter as d
3 min read
MongoDB vs MySQL
Differences between MongoDB and MySQL on various parameters are discussed below: What are MongoDB and MySQL? MongoDB MySQL MongoDB is an open-source database developed by MongoDB, Inc. MongoDB stores data in JSON-like documents that can vary in structure. It is a popular NoSQL database. MySQL is a popular open-source relational database management
2 min read
Difference between Oracle and MongoDB
1. Oracle : Oracle is a relational database management system (RDBMS). It was developed by Oracle Corporation in 1980. It is the first database designed for grid computing that provides the most flexible and cost-effective way to manage information and application. It runs on major platforms like Windows, Unix, Linux, and macOS. It is a relational
2 min read
Connecting MongoDB to Jupyter Notebook
MongoDB is one of the most famous NoSql databases. It is an open-source database. The simple meaning of the NoSql database is a non-relational database. i.e., It doesn't include the specific structure of databases such as tables and all like the relational database. So, you can design the schemas without any restrictions. Jupyter Notebook is also a
3 min read
Introduction about Node.js and MongoDB
NoSQL databases are databases that store and retrieve the data that is present in a non-tabular format. Depending on the format of the data stored, NoSQL databases are split into 4 major types: Key-Value Graph database Document-oriented Column family These databases are built to address the shortcomings of traditional RDBMS and provide high perform
4 min read
MongoDB | Delete Database using MongoShell
Prerequisite : MongoDB Introduction Short Description : A MongoDB Database is a container for all the collections, where Collection is a bunch of MongoDB documents similar to tables in RDBMS and Document is made of fields similar to a tuple in RDBMS, but it has a dynamic schema here. Example of a Document : { "Name" : "Aman", Age : 24, Gender : "Ma
2 min read
Create a Newsletter Sourcing Data using MongoDB
There are many news delivery websites available like ndtv.com. In this article, let us see the very useful and interesting feature of how to get the data from ndtv.com via scraping feature i.e. extracting the contents from ndtv.com and storing them into MongoDB. MongoDB is a NoSQL Documentum model database. Using Mongoose, Node JS, and Cheerio, the
7 min read
Difference between RDBMS and MongoDB
MongoDB is an open-source document-oriented database used for high volume data storage. It falls under the classification of a NoSQL database. NoSQL tool means that it doesn't utilize the usual rows and columns. MongoDB uses BSON (document storage format) which is a binary style of JSON documents. Features of MongoDB: Multiple Servers: It can run o
2 min read
How MongoDB works ?
MongoDB is an open-source document-oriented database. It is used to store a larger amount of data and also allows you to work with that data. MongoDB is not based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data, that's why known as NoSQL database. Here, the term ‘NoSQL
3 min read
MongoDB - Embedded Documents
MongoDB provides you a cool feature which is known as Embedded or Nested Document. Embedded document or nested documents are those types of documents which contain a document inside another document. Or in other words, when a collection has a document, this document contains another document, another document contains another sub-document, and so o
2 min read
MongoDB - Insert Single Document Using MongoShell
In MongoDB, insert operations are used to add new documents in the collection. If the collection does not exist, then the insert operations create the collection by inserting documents. Or if the collection exists, then insert operations and add new documents to the existing collection. You are allowed to add a single document in the collection usi
2 min read
MongoDB - Insert Multiple Document Using MongoShell
In MongoDB, insert operations are used to add new documents in the collection. If the collection does not exist, then the insert operations create the collection by inserting documents. Or if the collection exists, then insert operations add new documents in the existing collection. You are allowed to insert multiple documents in the collection by
2 min read
MongoDB - Update Single Document Using MongoShell
In MongoDB, you can update a single document in the collection using db.collection.updateOne() method. This method updates a document in the collection according to the filter. updateOne() is a mongo shell method, which can updates one document at a time. This method update the first document that satisfies the given condition in the collection. Or
4 min read
MongoDB - Update Multiple Documents Using MongoShell
In MongoDB, you can update multiple documents in the collection using db.collection.updateMany() method. This method updates all the documents in the collection that match the given filter. updateMany() is a mongo shell method, which can update multiple document. This method only accepts the documents that contain update operator expressions. updat
3 min read
MongoDB - Replace Documents Using MongoShell
In MongoDB, you are allowed to replace an existing document with a new document in the collection with the help of db.collection.replaceOne() method. This method will replace the existing document with the replacement document. replaceOne() is a mongo shell method, which only replaces one document at a time. The replacement document may contain dif
4 min read
MongoDB - Query Documents using Mongo Shell
MongoDB provides you read operations to retrieve documents from the collection or query a collection for a document. You can perform read operations using the db.collection.find() method. This method selects or views the documents from the collection and returns the cursor to the selected document. find() is a mongo shell method, which can be used
4 min read
MongoDB Projection
MongoDB provides a special feature that is known as Projection. It allows you to select only the necessary data rather than selecting whole data from the document. For example, a document contains 5 fields, i.e., { name: "Roma", age: 30, branch: EEE, department: "HR", salary: 20000 } But we only want to display the name and the age of the employee
2 min read
MongoDB - Query Embedded Documents Using Mongo Shell
MongoDB provides you read operations to retrieve embedded/nested documents from the collection or query a collection for a embedded/nested document. You can perform read operations using the db.collection.find() method. This method selects or views embedded/nested documents of the collection and returns the cursor to the selected document. Syntax:
3 min read
MongoDB AND operator ( $and )
MongoDB provides different types of logical query operators and $and operator is one of them. This operator is used to perform logical AND operation on the array of one or more expressions and select or retrieve only those documents that match all the given expression in the array. You can use this operator in methods like find(), update(), etc. ac
2 min read
MongoDB NOT operator ( $not )
MongoDB provides different types of logical query operators and $not operator is one of them. This operator is used to perform logical NOT operation on the specified operator expressions and select or retrieve only those documents that do not match the given operator expression. It also includes those documents that don't contain the field. You can
2 min read
MongoDB OR operator ( $or )
MongoDB provides different types of logical query operators and $or operator is one of them. This operator is used to perform logical OR operation on the array of two or more expressions and select or retrieve only those documents that match at least one of the given expression in the array. You can use this operator in methods like find(), update(
2 min read
MongoDB NOR operator ( $nor )
MongoDB provides different types of logical query operators and $nor operator is one of them. This operator is used to perform logical NOR operation on the array of one or more expressions and select or retrieve only those documents that do not match all the given expression in the array. You can use this operator in methods like find(), update(),
2 min read
How to get Distinct Documents from MongoDB using Node.js ?
MongoDB is a cross-platform, document-oriented database that works on the concept of collections and documents. It stores data in the form of key-value pairs and is a NoSQL database program. The term NoSQL means non-relational. MongoDB module: This module of Node.js is used for connecting the MongoDB database as well as used for manipulating the co
2 min read
MongoDB - Current Date Operator ($currentDate)
MongoDB provides different types of field update operators to update the values of the fields of the documents and $currentDate operator is one of them. This operator is used to set the value of a field to the current date (either as a timestamp or as a Date). The default type of $currentDate operator is a Date. This operator can also work with emb
2 min read