ANNOUNCEMENT: Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.
Learn more
Docs Menu

データベースコマンドを実行する

MongoDB PHP ライブラリは、一般的な データベースコマンドClientCollectionDatabase 、および クラスにわたるヘルパー メソッドを提供します。さらに、 MongoDB\Database::command()メソッドは、ヘルパー メソッドを持たないデータベースコマンドの実行に使用できます。

MongoDB\Database::command()メソッドは常に MongoDB\Driver\Cursor を返します オブジェクトは、コマンドカーソルを介して単一の結果ドキュメント 複数の結果を返すコマンドの実行をサポートする必要があるためです。

ほとんどのデータベースコマンドは結果ドキュメントを 1 つ返します。このドキュメントは、返されたカーソルを配列に変換し、その最初の要素にアクセスすることで取得できます。 次の例では、 pingコマンドを実行し、その結果ドキュメントを出力します。

<?php
$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()が使用されます。

<?php
$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.

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)が指定されます。

<?php
$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)
}
}