Docs HomeMongoDB Manual

cursor.forEach()

On this page本页内容

Description描述

cursor.forEach(function)
Important

mongosh Method

This page documents a mongosh method. This is not the documentation for a language-specific driver, such as Node.js.

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.迭代游标以将JavaScriptfunction应用于游标中的每个文档。

The forEach() method has the following prototype form:forEach()方法具有以下原型形式:

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

The forEach() method has the following parameter:forEach()方法具有以下参数:

Parameter参数Type类型Description描述
functionJavaScriptA JavaScript function to apply to each document from the cursor. 从游标应用于每个文档的JavaScript函数。The <function> signature includes a single argument that is passed the current document to process.<function>签名包括一个传递给当前文档以进行处理的参数。

Example实例

The following example invokes the forEach() method on the cursor returned by find() to print the name of each user in the collection:以下示例调用find()返回的游标上的forEach()方法,以打印集合中每个用户的名称:

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

See also: 另请参阅:

cursor.map() for similar functionality.用于类似的功能。