Jul 19, 2015

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 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 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 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 override using batchsize() or limit().

See following query

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

Note : In mongodb shell it is not possible to change 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 a SQL database.

example :

cursor.limit(10)

it will return 10 document

It there are more than 10 document in result then use cursor.next() to get other  10 document.