데이터베이스 명령 실행
개요
MongoDB PHP 라이브러리는 Client
, Database
, Collection
클래스 전반에 걸쳐 일반적인 데이터베이스 명령 에 대한 헬퍼 메서드를 제공합니다. 또한 MongoDB\Database::command()
메서드를 사용하여 헬퍼 메서드가 없는 데이터베이스 명령을 실행할 수 있습니다.
메서드는 MongoDB\Database::command()
항상 MongoDB\Driver\Cursor 를 반환합니다. 이는 명령 커서를 통해 단일 결과 문서 와 여러 결과를 반환하는 명령 실행을 지원해야 하기 때문입니다.
단일 결과 문서를 반환하는 명령
대부분의 데이터베이스 명령은 단일 결과 문서 를 반환하며, 이는 반환된 커서 를 배열 로 변환하고 첫 번째 요소에 액세스하여 얻을 수 있습니다. 다음 예시 에서는 핑 명령을 실행하고 결과 문서 를 출력합니다.
$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 protocol 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 readPreference 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.
다음 예시에서는 cluster에 연결하고 secondaryPreferred
을 클라이언트의 기본 읽기 설정 (read preference)으로 지정합니다. 그런 다음 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) } }