データベースコマンドを実行する
Overview
MongoDB PHP ライブラリは、一般的な データベースコマンドClient
のCollection
、Database
、および クラスにわたるヘルパー メソッドを提供します。さらに、 MongoDB\Database::command()
メソッドは、ヘルパー メソッドを持たないデータベースコマンドの実行に使用できます。
MongoDB\Database::command()
メソッドは常に MongoDB\Driver\Cursor を返します オブジェクトは、コマンドカーソルを介して単一の結果ドキュメント と 複数の結果を返すコマンドの実行をサポートする必要があるためです。
単一の結果ドキュメントを返すコマンド
ほとんどのデータベースコマンドは結果ドキュメントを 1 つ返します。このドキュメントは、返されたカーソルを配列に変換し、その最初の要素にアクセスすることで取得できます。 次の例では、 pingコマンドを実行し、その結果ドキュメントを出力します。
$database = (new MongoDB\Client)->test; $cursor = $database->command(['ping' => 1]); var_dump($cursor->toArray()[0]);
出力は次のようになります。
object(MongoDB\Model\BSONDocument)#11 (1) { ["storage":"ArrayObject":private]=> array(1) { ["ok"]=> float(1) } }
複数の結果を生成するコマンド
一部のデータベースコマンドは、複数の結果を持つカーソルを返します。 次の例ではlistCollectionsを実行します。これにより、 test
データベース内の各コレクションの結果ドキュメントを含むカーソルが返され、 foreach
ループを使用して結果が反復処理されます。 この例は、説明のためのものであることに注意してください。アプリケーションでは通常、実際にはMongoDB\Database::listCollections()
が使用されます。
$database = (new MongoDB\Client)->test; $cursor = $database->command(['listCollections' => 1]); foreach ($cursor as $collection) { echo $collection['name'], "\n"; }
出力は、次のようになります。
persons posts zips
注意
At the プロトコル level, commands that yield multiple results via a cursor will return a single result document with the essential ingredients for constructing the cursor (i.e. the cursor's ID, namespace, and an optional first batch of results). If the MongoDB\Driver\Manager::executeCommand() method in the extension detects such a response, it will construct an iterable command cursor and return it instead of the raw result document. If necessary, raw result documents can still be observed using command monitoring.
カスタム読み込み設定(read preference)の指定
Write commands, such as createUser,
can only be executed on a writable server (e.g. primary replica set
member). Command helper methods in the MongoDB PHP Library, such as
MongoDB\Database::drop()
, know to apply their own 読み込み設定 (read preference) if necessary. However, the MongoDB\Database::command()
method is a generic method and defaults to the read preference of the Database
object on which it is invoked. When necessary, the readPreference
option may
be used to override the default read preference.
次の例では、クラスターに接続し、クライアントのデフォルトの読み取り設定としてsecondaryPreferred
を指定しています。 次に、 test
データベースでcreateUser
コマンドを実行するときに、 primary
読み込み設定(read preference)が指定されます。
$client = new MongoDB\Client( 'mongodb+srv://cluster0.example.com', ['readPreference' => 'secondaryPreferred'] ); $client->test; $cursor = $db->command( [ 'createUser' => 'username', 'pwd' => 'password', 'roles' => ['readWrite'], ], [ 'readPreference' => new MongoDB\Driver\ReadPreference('primary'), ] ); var_dump($cursor->toArray()[0]);
出力は次のようになります。
object(MongoDB\Model\BSONDocument)#8 (1) { ["storage":"ArrayObject":private]=> array(1) { ["ok"]=> float(1) } }