AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

cursor.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.

  • MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン

  • MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン

このメソッドの構文は次のとおりです。

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

このメソッドは次のフィールドを受け入れます。

フィールド
タイプ
説明

function

JavaScript コード

カーソルから返される各ドキュメントに適用する関数。関数シグネチャには、カーソルから読み取られた現在のドキュメントを格納する 1 つのフィールドが含まれます。

users コレクションを次のように作成します。

db.users.insertMany( [
{ name: "John" },
{ name: "Jane" }
] )

次の例では、find() メソッドで forEach() を使用して、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()を参照してください。