Skip to content

Foreach 1 #538

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 11, 2013
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 39 additions & 7 deletions source/reference/method/cursor.forEach.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,49 @@ cursor.forEach()

.. default-domain:: mongodb

.. method:: cursor.forEach(function)
.. method:: cursor.forEach(<function>)

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

Provides the ability to loop or iterate over the cursor returned by
a :method:`db.collection.find()` query and returns each result on the
shell. Specify a JavaScript function as the argument for the
:method:`cursor.forEach()` function. Consider the following example:
The :method:`~cursor.forEach()` method accepts the following
argument:

:param <function>:

JavaScript function to apply to each document from the
cursor. The ``<function>`` signature includes a single argument
that is passed the current document to process, as in the
following prototype:

.. code-block:: javascript

function(doc) {
...
}

However, if the signature is missing the argument, you can
access the document using the reserved
``arguments`` [#arguments]_ variable within the function,
specifically ``arguments[0]``, as in the following prototype:

.. code-block:: javascript

function() {
doc = arguments[0];
...
}

.. [#arguments] The ``arguments`` variable is an array
and thus, you can access ``arguments.length`` attribute to
determine the number of arguments.

The following example invokes the :method:`~cursor.forEach()` method
on the cursor returned by :method:`~db.collection.find()` to print
the name of each user in the collection:

.. code-block:: javascript

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

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