Database Manual / Reference / mongosh Methods / Cursors

cursor.forEach() (mongosh method方法)

Definition定义

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.本页记录了一种mongosh方法。这不是针对特定语言驱动程序(如Node.js)的文档。

For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.有关MongoDB API驱动程序,请参阅特定语言的MongoDB驱动程序文档

Iterates the cursor to apply a JavaScript function to each document from the cursor.迭代游标,将JavaScriptfunction应用于游标中的每个文档。

Compatibility兼容性

This method is available in deployments hosted in the following environments:此方法在以下环境中托管的部署中可用:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务

Note

This command is supported in all MongoDB Atlas clusters. 所有MongoDB Atlas集群都支持此命令。For information on Atlas support for all commands, see Unsupported Commands.有关Atlas支持所有命令的信息,请参阅不支持的命令

  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

The method has the following syntax:该方法具有以下语法:

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

Method Fields方法字段

The method accepts the following field:该方法接受以下字段:

Field字段Type类型Description描述
functionJavaScript codeFunction 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:创建users集合:

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. 以下示例使用forEach()find()方法打印从users集合中读取的用户名。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:mongosh 2.1.0开始,您还可以使用for-of循环。以下示例返回与前一个示例相同的结果:

for ( const myDoc of db.users.find() ) {
print( "User name: " + myDoc.name )
}

Learn More了解更多

For a method that has similar functionality, see cursor.map().有关具有类似功能的方法,请参阅cursor.map()