Iterate
From NoSQLZoo
MongoDB's find()
method returns a cursor object which can be iterated using while
, hasNext()
and next
, or by using forEach()
.
Iterating countries in South America stored in the 'world' collection.
let cursor = db.world.find({continent:"South America"}) while (cursor.hasNext()) { printjson(cursor.next()); }
let cursor = db.world.find({continent:"South America"}) cursor.forEach(printjson);
Cursors can also be used to find the nth record in a result as an alternative to .find().skip(n).limit(1)
Find the 3rd result of the previous example.
db.world.find({continent:"South America"}).toArray()[3]