Navigation
This version of the documentation is archived and no longer supported.

Iterate a Cursor in the mongo Shell

The db.collection.find() method returns a cursor. To access the documents, you need to iterate the cursor. However, in the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents in the results. The following describes ways to manually iterate the cursor to access the documents or to use the iterator index.

Manually Iterate the Cursor

In the mongo shell, when you assign the cursor returned from the find() method to a variable using the var keyword, the cursor does not automatically iterate.

You can call the cursor variable in the shell to iterate up to 20 times [1] and print the matching documents, as in the following example:

var myCursor = db.inventory.find( { type: 'food' } );

myCursor

You can also use the cursor method next() to access the documents, as in the following example:

var myCursor = db.inventory.find( { type: 'food' } );
var myDocument = myCursor.hasNext() ? myCursor.next() : null;

if (myDocument) {
    var myItem = myDocument.item;
    print(tojson(myItem));
}

As an alternative print operation, consider the printjson() helper method to replace print(tojson()):

if (myDocument) {
    var myItem = myDocument.item;
    printjson(myItem);
}

You can use the cursor method forEach() to iterate the cursor and access the documents, as in the following example:

var myCursor =  db.inventory.find( { type: 'food' } );

myCursor.forEach(printjson);

See JavaScript cursor methods and your driver documentation for more information on cursor methods.

[1]You can use the DBQuery.shellBatchSize to change the number of iteration from the default value 20. See Executing Queries for more information.

Iterator Index

In the mongo shell, you can use the toArray() method to iterate the cursor and return the documents in an array, as in the following:

var myCursor = db.inventory.find( { type: 'food' } );
var documentArray = myCursor.toArray();
var myDocument = documentArray[3];

The toArray() method loads into RAM all documents returned by the cursor; the toArray() method exhausts the cursor.

Additionally, some drivers provide access to the documents by using an index on the cursor (i.e. cursor[index]). This is a shortcut for first calling the toArray() method and then using an index on the resulting array.

Consider the following example:

var myCursor = db.inventory.find( { type: 'food' } );
var myDocument = myCursor[3];

The myCursor[3] is equivalent to the following example:

myCursor.toArray() [3];