Skip to content

Commit f20a604

Browse files
author
Ed Costello
committed
Merge pull request #538 from kay-kim/foreach-1
Foreach 1
2 parents f34c0bc + d4ef057 commit f20a604

File tree

1 file changed

+39
-7
lines changed

1 file changed

+39
-7
lines changed

source/reference/method/cursor.forEach.txt

Lines changed: 39 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,49 @@ cursor.forEach()
44

55
.. default-domain:: mongodb
66

7-
.. method:: cursor.forEach(function)
7+
.. method:: cursor.forEach(<function>)
88

9-
:param function: function to apply to each document visited by the cursor.
9+
The :method:`~cursor.forEach()` method iterates the cursor to apply
10+
a JavaScript ``<function>`` to each document from the cursor.
1011

11-
Provides the ability to loop or iterate over the cursor returned by
12-
a :method:`db.collection.find()` query and returns each result on the
13-
shell. Specify a JavaScript function as the argument for the
14-
:method:`cursor.forEach()` function. Consider the following example:
12+
The :method:`~cursor.forEach()` method accepts the following
13+
argument:
14+
15+
:param <function>:
16+
17+
JavaScript function to apply to each document from the
18+
cursor. The ``<function>`` signature includes a single argument
19+
that is passed the current document to process, as in the
20+
following prototype:
21+
22+
.. code-block:: javascript
23+
24+
function(doc) {
25+
...
26+
}
27+
28+
However, if the signature is missing the argument, you can
29+
access the document using the reserved
30+
``arguments`` [#arguments]_ variable within the function,
31+
specifically ``arguments[0]``, as in the following prototype:
32+
33+
.. code-block:: javascript
34+
35+
function() {
36+
doc = arguments[0];
37+
...
38+
}
39+
40+
.. [#arguments] The ``arguments`` variable is an array
41+
and thus, you can access ``arguments.length`` attribute to
42+
determine the number of arguments.
43+
44+
The following example invokes the :method:`~cursor.forEach()` method
45+
on the cursor returned by :method:`~db.collection.find()` to print
46+
the name of each user in the collection:
1547

1648
.. code-block:: javascript
1749

18-
db.users.find().forEach( function(u) { print("user: " + u.name); } );
50+
db.users.find().forEach( function(myDoc) { print( "user: " + myDoc.name ); } );
1951

2052
.. seealso:: :method:`cursor.map()` for similar functionality.

0 commit comments

Comments
 (0)