cursor.forEach()
On this page
Definition
cursor.forEach(function)
Important
mongosh Method
This is a
mongosh
method. This is not the documentation forNode.js
or other programming language specific driver methods.In most cases,
mongosh
methods work the same way as the legacymongo
shell methods. However, some legacy methods are unavailable inmongosh
.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.
Syntax
The method has the following syntax:
db.collection.find().forEach( <function> )
Method Fields
The method accepts the following field:
Field | Type | Description |
---|---|---|
function | JavaScript code | Function to apply to each document returned from the cursor. The
function signature includes one field that stores the current
document that is read from the cursor. |
Examples
Create the users
collection:
db.users.insertMany( [ { name: "John" }, { name: "Jane" } ] )
The following example uses forEach()
with the
find()
method to print the user names that are
read from the users
collection. myDoc
stores the current
document.
db.users.find().forEach( function( myDoc ) { print( "User name: " + myDoc.name ) } )
Example output:
User name: John User name: Jane
Starting in mongosh
2.1.0, you can also use for-of
loops. The following example returns the same results as the previous
example:
for ( const myDoc of db.users.find() ) { print( "User name: " + myDoc.name ) }
Learn More
For a method that has similar functionality, see cursor.map()
.