对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

游标.forEach()(mongosh方法)

cursor.forEach(function)

重要

mongosh 方法

This page documents a mongosh method. 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.

该方法的语法如下:

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

该方法接受以下字段:

字段
类型
说明

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()。