Cookies help us deliver our services. By using our services, you agree to our use of cookies. More information

Iterate

From NoSQLZoo
Revision as of 00:34, 9 April 2018 by 40166222 (talk | contribs) (Created page with "{{TopTenTips}} MongoDB's <code>find()</code> method returns a cursor object which can be iterated using <code>while</code>, <code>hasNext()</code> and <code>next</code>, or by...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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]