Definition定义
cursor.forEach(function)-
Important
mongosh
Method方法This page documents a本页记录了一种mongoshmethod. 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迭代游标,将JavaScriptfunctionto each document from the cursor.function应用于游标中的每个文档。
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:该方法接受以下字段:
function | JavaScript code |
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()。