cursor.forEach()

On this page本页内容

Description描述

cursor.forEach(function)
Important重要
mongosh Method

This is a mongosh method. This is not the documentation for Node.js or other programming language specific driver methods.

In most cases, mongosh methods work the same way as the legacy mongo shell methods. However, some legacy methods are unavailable in mongosh.

For the legacy mongo shell documentation, refer to the documentation for the corresponding MongoDB Server release:

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.循环游标以将JavaScript函数应用于游标中的每个文档。

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.用于类似功能。

←  cursor.explain()cursor.hasNext() →