개요
이 가이드 에서는 MongoDB PHP 라이브러리를 사용하여 커서 에서 데이터에 액세스 하는 방법을 학습 수 있습니다.
커서 는 읽기 작업의 결과를 반복 가능한 배치로 반환하는 메커니즘입니다. 커서는 모든 문서를 한 번에 반환하는 대신 주어진 시간에 문서의 하위 집합만 보유하여 메모리 소비와 서버 요청 수를 모두 줄입니다.
Whenever the MongoDB PHP Library performs a read operation by using the MongoDB\Collection::find() method, it returns the matching documents in a MongoDB\Driver\Cursor instance. The Cursor class implements PHP's Iterator interface, which provides more control over iteration and greater compatibility with PHP functions that work with iterables. MongoDB cursors support only forward iteration, so you cannot rewind a cursor or use a foreach loop multiple times.
샘플 데이터
The examples in this guide use the restaurants collection in the sample_restaurants database from the Atlas sample datasets. To access this collection from your PHP application, instantiate a MongoDB\Client that connects to an Atlas cluster and assign the following value to your $collection variable:
$collection = $client->sample_restaurants->restaurants;
무료 MongoDB 배포서버 생성하고 샘플 데이터 세트를 로드하는 방법을 학습하려면, MongoDB 시작하기 가이드 참조하세요.
반복적으로 커서 내용에 액세스
MongoDB\Driver\Cursor 클래스는 Iterator 인터페이스를 구현하므로 foreach 루프를 사용하여 해당 내용을 반복할 수 있습니다.
다음 예시 에서는 MongoDB\Collection::find() 메서드를 사용하여 name 필드 값이 'Dunkin' Donuts' 인 모든 문서를 조회 합니다. 그런 다음 find() 메서드에서 반환된 커서 에서 각 문서 를 인쇄합니다.
$cursor = $collection->find(['name' => 'Dunkin\' Donuts']); foreach ($cursor as $doc) { echo json_encode($doc), PHP_EOL; }
문서 개별 조회
커서 에서 개별 문서 를 조회 하려면 MongoDB\Driver\Cursor 인스턴스 에서 current() 메서드를 호출합니다. 이 메서드는 커서 가 처음에 가리키는 문서 를 반환합니다. next() 메서드를 호출하여 커서 를 계속 진행할 수 있으며, 이 메서드는 커서 가 검색된 다음 문서 를 점 키도록 지시합니다.
다음 예시 에서는 name 필드 값이 'Dunkin' Donuts' 인 모든 문서를 찾습니다. 그런 다음 커서 에서 current() 메서드를 호출하여 첫 번째로 조회 문서 를 인쇄합니다.
$cursor = $collection->find(['name' => 'Dunkin\' Donuts']); $cursor->rewind(); echo json_encode($cursor->current());
모든 문서 검색
경고
쿼리에서 반환되는 문서의 수와 크기가 사용 가능한 애플리케이션 메모리를 초과하면 프로그램이 충돌합니다. 큰 결과 세트가 예상되는 경우 커서에 반복적으로 액세스합니다.
커서 에서 모든 문서를 조회 하려면 다음 방법 중 하나를 사용하여 커서 를 배열 로 변환합니다.
MongoDB\\Driver\\Cursor::toArray():MongoDB\Driver\Cursor객체iterator_to_array():MongoDB\Driver\Cursor객체 를 매개변수로 전달
다음 예시 에서는 커서 에서 toArray() 메서드를 호출하여 결과를 배열 에 저장 합니다.
$cursor = $collection->find(['name' => 'Dunkin\' Donuts']); $resultArray = $cursor->toArray();
테일 커서(tailable cursor)
클라이언트 초기 내용을 읽은 후에도 커서 열린 상태로 유지되도록 하려면 tailable cursor 사용할 수 있습니다. 고정 사이즈 컬렉션을 쿼리 하려면 테일 커서(tailable cursor)를 사용하는 것이 좋습니다.
커서의 초기 결과 설정하다 읽은 후에 루프가 종료되므로 foreach 루프를 사용하여 tailable cursor 반복할 수 없습니다. 두 번째 foreach 루프를 사용하여 tailable cursor 계속 반복하는 경우 PHP 라이브러리는 커서 되감으려고 시도한 다음 오류를 생성합니다. 대신 반복자 인터페이스의 메서드를 사용하여 tailable cursor) 에서 결과를 조회 해야 합니다.
tailable cursor 만들려면 배열 에서 cursorType 옵션을 MongoDB\Operation\Find::TAILABLE (으)로 설정하다 . 그런 다음 배열 MongoDB\Collection::find() 메서드에 옵션 매개변수로 전달합니다.
테일 커서(tailable cursor) 예시
이 섹션에서는 동시에 실행 수 있는 다음과 같은 샘플 스크립트를 제공합니다.
A producer script that creates a capped collection and inserts documents into it
고정 사이즈 컬렉션 에서 문서를 읽기 위해 tailable cursor 생성하는 소비자 스크립트
컬렉션 생성 및 채우기
다음 예시 vegetables 이라는 고정 사이즈 컬렉션 만들고 컬렉션 에 추가 문서 삽입하기 전에 5 초 동안 기다립니다.
$db = $client->db; $db->createCollection( 'vegetables', ['capped' => true, 'size' => 1024 * 1024], ); $vegetables = [ ['name' => 'cauliflower', 'createdAt' => new MongoDB\BSON\UTCDateTime()], ['name' => 'zucchini', 'createdAt' => new MongoDB\BSON\UTCDateTime()], ]; $collection = $db->vegetables; $result = $collection->insertMany($vegetables); sleep(5); $collection->insertOne(['name' => 'carrot', 'createdAt' => new MongoDB\BSON\UTCDateTime()]);
테일 커서(tailable cursor) 만들기
While the preceding code example is running, use the following code to create a tailable cursor and retrieve all documents in the vegetables collection:
$cursor = $collection->find([], ['cursorType' => MongoDB\Operation\Find::TAILABLE]); $cursor->rewind(); $docsFound = 0; while ($docsFound < 3) { if ($cursor->valid()) { $doc = $cursor->current(); echo json_encode($doc), PHP_EOL; $docsFound++; } $cursor->next(); }
이 코드는 컬렉션 에 있는 두 개의 초기 문서를 인쇄하지만 while 루프는 세 번째 문서 받을 때까지 종료되지 않습니다. next() 메서드는 코드가 추가 커서 결과를 기다리도록 합니다.
팁
테일 커서(tailable cursor)에 학습 보려면 MongoDB Server 매뉴얼에서 테일 커서 (tailable cursor)를 참조하세요.
추가 정보
읽기 작업에 학습 보려면 데이터 조회 가이드 를 참조하세요.
커서에 학습 보려면 확장 API 문서의 다음 페이지를 참조하세요.
API 문서
find() 메서드에 학습 보려면 MongoDB\Collection::find()에 대한 API 설명서를 참조하세요.