Difference between revisions of "Iterate"
From NoSQLZoo
(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...") |
m |
||
(3 intermediate revisions by the same user not shown) | |||
Line 3: | Line 3: | ||
<div class="q nonum" data-lang="mongo"> | <div class="q nonum" data-lang="mongo"> | ||
<p class="strong">Iterating countries in South America stored in the 'world' collection.</p> | <p class="strong">Iterating countries in South America stored in the 'world' collection.</p> | ||
− | <pre class=def> | + | <pre class="def"><nowiki> |
− | let cursor = db.world.find({continent:"South America"}) | + | let cursor = db.world.find({continent: "South America"}); |
while (cursor.hasNext()) { | while (cursor.hasNext()) { | ||
printjson(cursor.next()); | printjson(cursor.next()); | ||
− | } | + | }</nowiki></pre> |
− | </pre> | ||
</div> | </div> | ||
<div class="q nonum" data-lang="mongo"> | <div class="q nonum" data-lang="mongo"> | ||
− | <pre class=def> | + | <pre class="def"><nowiki> |
− | let cursor = db.world.find({continent:"South America"}) | + | let cursor = db.world.find({continent: "South America"}); |
− | cursor.forEach(printjson); | + | cursor.forEach(printjson);</nowiki></pre> |
− | </pre> | ||
</div> | </div> | ||
− | Cursors can also be used to find the '''n'''th record in a result as an alternative to <code>.find().skip(n).limit(1)</code> | + | Cursors can also be converted to other JavaScript collection types, such as arrays.<br/> |
+ | In the following example an array is used to find the '''n'''th record in a result as an alternative to <code>.find().skip(n).limit(1)</code> | ||
<div class="q nonum" data-lang="mongo"> | <div class="q nonum" data-lang="mongo"> | ||
<p class="strong">Find the 3rd result of the previous example.</p> | <p class="strong">Find the 3rd result of the previous example.</p> | ||
− | <pre class=def> | + | <pre class="def"><nowiki> |
− | db.world.find({continent:"South America"}).toArray()[3] | + | db.world.find({continent:"South America"}).toArray()[3];</nowiki></pre> |
− | </pre> | ||
</div> | </div> |
Latest revision as of 16:34, 18 July 2018
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 converted to other JavaScript collection types, such as arrays.
In the following example an array is 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];