このチュートリアルでは、カーソル内のドキュメントにアクセスする方法を説明します。
このタスクについて
カーソル内のドキュメントにアクセスするには、カーソルを手動で反復処理するか、toArray() メソッドを使用します。
このチュートリアルでは、次の方法について概説します。
letキーワードを使用してカーソルを変数として保存します。toArray()メソッドを使用して、カーソル ドキュメントを配列として返してアクセスします。
バッチ サイズ
A cursor returns documents in batches. By default, mongosh displays 20 documents per cursor iteration. You can use config.set("displayBatchSize") to change it, if this is too much or too little for your needs.
始める前に
Install mongosh.
Connect to a deployment.
新しいコレクションにドキュメントを挿入します。
デフォルトの test データベースを使用してドキュメントを新しいコレクションに挿入するには、mongosh を使用します。
db.users.insertMany( [ { _id: 0, type: "admin", email: "admin@example.com", name: "Admin User" }, { _id: 1, type: "user", email: "user1@example.com", name: "Test User 1" }, { _id: 2, type: "user", email: "user2@example.com", name: "Test User 2" } ] )
例
カーソルを保存するには、 let
In mongosh, the cursor does not automatically iterate when you assign it to a variable using the let keyword.
let myCursor = db.users.find( { type: "user" } )
shell でカーソル変数を呼び出して、一致するドキュメントを出力できます。
myCursor
返されたカーソルが let キーワードを使用して変数に割り当てられていない場合、カーソルはバッチ サイズまで自動的に繰り返し処理され、最初のバッチするの結果が出力されます。
db.users.find( { type: "user" } )
を使用してカーソル内のドキュメントにアクセスする next()
カーソル メソッド next() を使用してドキュメントにアクセスすることもできます。next() は、カーソルが現在指しているドキュメントを返し、カーソルを次のドキュメントに移動します。
let myCursor = db.users.find( { type: "user" } ) myCursor.next()
を使用してカーソル内のドキュメントにアクセスする hasNext()
カーソル メソッド hasNext() は true または false を返して、カーソルから返されるドキュメントが他にもあるかどうかを示します。
let myCursor = db.users.find( { type: "user" } ) myCursor.hasNext()
hasNext() メソッドと next() メソッドを使用して、printjson() ヘルパーを使い、カーソルから残りのすべてのドキュメントを印刷できます。
let myCursor = db.users.find( { type: "user" } ) while ( myCursor.hasNext() ) { printjson( myCursor.next() ) }
を使用してカーソル内のドキュメントにアクセスする forEach()
同様に、カーソル内の各ドキュメントに対して forEach() カーソル メソッドを使用し、printjson() などのヘルパーを適用することができます。
let myCursor = db.users.find( { type: "user" } ) myCursor.forEach( myDocument => printjson(myDocument) )
Starting in mongosh 2.1.0, you can also use for-of loops to iterate the cursor. The following example returns the same results as the previous example.
let myCursor = db.users.find( { type: "user" } ) for ( let myDocument of myCursor ) { printjson( myDocument ) }
See JavaScript cursor methods and your driver documentation for more information on cursor methods.
を使用してカーソル内のドキュメントにアクセスする toArray()
In mongosh, use the toArray() method to iterate the cursor and return the documents in an array.
let myCursor = db.users.find( { type: "user" } ) let documentArray = myCursor.toArray() documentArray
結果のドキュメント配列には、従来の配列としてアクセスすることができます。
let myCursor = db.users.find( { type: "user" } ) let documentArray = myCursor.toArray() documentArray[1]
toArray() メソッドは、カーソルによって返されるすべてのドキュメントを RAM に読み込み、カーソルを使い切ります。
一部のドライバーでは、カーソルのインデックス(例: cursor[index])を使用してドキュメントにアクセスします。これは、最初に toArray() メソッドを呼び出し、次に結果の配列のインデックスを使用するショートカットです。
let myCursor = db.users.find( { type: "user" } ) myCursor.toArray() [1]