What is the cursor in mongodb


As we know to fetch records we have to use find() method in MongoDB. db.collection.find() method is the primary method for the read operation. This method queries a collection and returns a cursor to the queried document.

For the query performance, we need to iterate cursor, for example, suppose we have a collection with 20 million records and fire below the query 


db.Books.find({"price":{$gte:200,$lte:300}})

this query will return data in more than lack, it may create an issue of the performance so we need to iterate of the cursor here.

In MongoDB shell, if the returned cursor is not assigned to a variable like var keyword, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents in the results. but if we are using it with c# then it will ask for iteration of cursor due to performance.


Note: You can use the DBQuery.shellBatchSize to change the number of iteration from the default value 20.

Cursor Behavior

Closure of inactive cursor: Server close to cursor automatically after 10 minutes of inactivity or the client has exhausted the cursor. To override this behavior, you can specify the noTimeout flag in your query using cursor.addOption();

Cursor Batches: Server returns the query result in batches, the batch size may be overridden using batchsize() or limit().

See the following query

db.Books.find().batchSize(10)

Note: In MongoDB shell, it is not possible to change the default batch(20) size using method batchSize().
Use the limit() method on a cursor to specify the maximum number of documents the cursor will return. limit() is analogous to the LIMIT statement in an SQL database.

example :

cursor.limit(10)

it will return 10 document

It there is more than 10 document as result then use cursor.next() to get the other  10 documents.

Related Posts

What is the Use of isNaN Function in JavaScript? A Comprehensive Explanation for Effective Input Validation

In the world of JavaScript, input validation is a critical aspect of ensuring that user-provided data is processed correctly. One indispensa...