Docs Menu

Docs HomeDevelop ApplicationsMongoDB Manual

cursor.forEach()

On this page

  • Description
  • Example
cursor.forEach(function)

Important

mongosh Method

This is a mongosh method. This is not the documentation for Node.js or other programming language specific driver methods.

In most cases, mongosh methods work the same way as the legacy mongo shell methods. However, some legacy methods are unavailable in mongosh.

For the legacy mongo shell documentation, refer to the documentation for the corresponding MongoDB Server release:

For MongoDB API drivers, refer to the language specific MongoDB driver documentation.

Iterates the cursor to apply a JavaScript function to each document from the cursor.

The forEach() method has the following prototype form:

db.collection.find().forEach(<function>)

The forEach() method has the following parameter:

Parameter
Type
Description
function
JavaScript
A 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.

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

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

Tip

See also:

cursor.map() for similar functionality.

←  cursor.explain()cursor.hasNext() →

On this page