定義
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 コード | カーソルから返される各ドキュメントに適用する関数。関数シグネチャには、カーソルから読み取られた現在のドキュメントを格納する 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()を参照してください。