Skip to content

Commit d4d5791

Browse files
committed
DOCS-918 forEach javascript function information
1 parent b1da809 commit d4d5791

File tree

1 file changed

+44
-6
lines changed

1 file changed

+44
-6
lines changed

source/reference/method/cursor.forEach.txt

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,53 @@ cursor.forEach()
66

77
.. 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
10+
to apply 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+
which 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+
Consider the following example which appends the
45+
:method:`~cursor.forEach()` method to a
46+
:method:`~db.collection.find()` query to iterate through the cursor
47+
returned from the :method:`~db.collection.find()` and apply the
48+
function to each document:
1549

1650
.. code-block:: javascript
1751

18-
db.users.find().forEach( function(u) { print("user: " + u.name); } );
52+
db.users.find().forEach( function(myDoc) { print( "user: " + myDoc.name ); } );
53+
54+
The example finds all documents in the ``users`` collection and
55+
applies function to each document in order to print the name from each
56+
document.
1957

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

0 commit comments

Comments
 (0)