定义
cursor.forEach(function)重要
mongosh 方法
This page documents a
mongoshmethod. This is not the documentation for a language-specific driver, such as Node.js.如需了解 MongoDB API 驱动程序,请参阅特定语言的 MongoDB 驱动程序文档。
迭代游标以将 JavaScript
function应用到游标处的每个文档。
兼容性
此方法可用于以下环境中托管的部署:
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
注意
This command is supported in all MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
语法
该方法的语法如下:
db.collection.find().forEach( <function> )
方法字段
该方法接受以下字段:
字段 | 类型 | 说明 |
|---|---|---|
| JavaScript 代码 | 应用于从游标返回的每个文档的函数。函数签名包括一个字段,用于存储从游标读取的当前文档。 |
示例
创建 users 集合:
db.users.insertMany( [ { name: "John" }, { name: "Jane" } ] )
以下示例使用 forEach() 和 find() 方法打印从 users 集合中读取的用户名。myDoc 存储当前文档。
db.users.find().forEach( function( myDoc ) { print( "User name: " + myDoc.name ) } )
示例输出:
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 ) }
了解详情
有关具有类似功能的方法,请参阅 cursor.map()。