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

myCursor.forEach(printjson); 

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

## 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]; 

## 3.3.8 Analyze Query Performance 

The cursor.explain("executionStats") and the db.collection.explain("executionStats") methods provide statistics about the performance of a query. This data output can be useful in measuring if and how a query uses an index. 

db.collection.explain() provides information on the execution of other operations, such as db.collection.update() . See db.collection.explain() for details. 

## Evaluate the Performance of a Query 

Consider a collection inventory with the following documents: 

{ "_id" : 1, "item" : "f1", type: "food", quantity: 500 } { "_id" : 2, "item" : "f2", type: "food", quantity: 100 } { "_id" : 3, "item" : "p1", type: "paper", quantity: 200 } { "_id" : 4, "item" : "p2", type: "paper", quantity: 150 } { "_id" : 5, "item" : "f3", type: "food", quantity: 300 } { "_id" : 6, "item" : "t1", type: "toys", quantity: 500 } { "_id" : 7, "item" : "a1", type: "apparel", quantity: 250 } { "_id" : 8, "item" : "a2", type: "apparel", quantity: 400 } { "_id" : 9, "item" : "t2", type: "toys", quantity: 50 } { "_id" : 10, "item" : "f4", type: "food", quantity: 75 } 

