개요
이 가이드 에서는 MongoDB PHP 라이브러리를 사용하여 읽기 작업 을 통해 MongoDB 컬렉션 에서 데이터를 조회 하는 방법을 학습 수 있습니다. 컬렉션 에서 MongoDB\Collection::find()
또는 MongoDB\Collection::findOne()
메서드를 호출하여 기준의 설정하다 과 일치하는 문서를 조회 할 수 있습니다.
샘플 데이터
이 가이드 의 예제에서는 Atlas 샘플 데이터 세트 의 sample_training
데이터베이스 에 있는 companies
컬렉션 을 사용합니다. PHP 애플리케이션 에서 이 컬렉션 에 액세스 하려면 Atlas cluster 에 연결하는 MongoDB\Client
를 인스턴스화하고 $collection
변수에 다음 값을 할당합니다.
$collection = $client->sample_training->companies;
무료 MongoDB Atlas cluster 를 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 보려면 Atlas 시작하기 가이드 를 참조하세요.
문서 찾기
MongoDB PHP 라이브러리에는 컬렉션 에서 문서를 검색하는 두 가지 메서드 MongoDB\Collection::findOne()
및 MongoDB\Collection::find()
가 포함되어 있습니다. 이러한 메서드는 쿼리 필터하다 를 사용하여 하나 이상의 일치하는 문서를 반환합니다. 쿼리 필터하다 는 운전자 가 쿼리 에서 문서를 조회 하는 데 사용하는 검색 기준을 지정합니다.
팁
쿼리 필터에 학습 보려면 쿼리 지정 가이드 를 참조하세요.
하나의 문서 찾기
컬렉션 에서 단일 문서 를 찾으려면 MongoDB\Collection::findOne()
메서드를 호출하고 찾으려는 문서 의 기준을 지정하는 쿼리 필터하다 를 전달합니다.
findOne()
메서드는 array
, object
또는 null
값을 반환합니다. 쿼리 필터하다 가 문서 와 일치하면 메서드는 해당 문서 가 포함된 array|object
인스턴스 를 반환합니다. 반환 유형은 typeMap
옵션의 값에 따라 달라집니다. 쿼리 필터하다 가 어떤 문서와도 일치하지 않으면 메서드는 null
를 반환합니다.
팁
typeMap
와 같은 findOne()
옵션에 학습 보려면 이 가이드 의 찾기 동작 수정 섹션을 참조하세요.
쿼리 필터하다 가 둘 이상의 문서 와 일치하는 경우 findOne()
메서드는 조회된 결과에서 첫 번째 로 일치하는 문서 를 반환합니다.
다음 예시 에서는 findOne()
메서드를 사용하여 name
필드 의 값이 'LinkedIn'
인 첫 번째 문서 를 찾습니다.
$document = $collection->findOne(['name' => 'LinkedIn']); echo json_encode($document), PHP_EOL;
{"_id":{"$oid":"..."},"name":"LinkedIn","permalink":"linkedin","crunchbase_url": "http:\/\/www.crunchbase.com\/company\/linkedin","homepage_url":"http:\/\/linkedin.com", ... }
여러 문서 찾기
컬렉션에서 여러 문서를 찾으려면 검색하려는 문서의 기준을 지정하는 MongoDB\Collection::find()
메서드에 쿼리 필터를 전달합니다.
다음 예시 에서는 find()
메서드를 사용하여 founded_year
필드 에 1970
값이 있는 모든 문서를 찾습니다.
$results = $collection->find(['founded_year' => 1970]);
find()
메서드는 MongoDB\Driver\Cursor
인스턴스 를 반환하며, 이를 반복하여 일치하는 문서를 볼 수 있습니다. 커서 는 애플리케이션 이 주어진 시간에 데이터베이스 결과의 하위 집합만 메모리에 유지하면서 데이터베이스 결과를 반복할 수 있는 메커니즘입니다. 커서는 find()
메서드가 많은 양의 문서를 반환할 때 유용합니다.
다음 예제와 같이 foreach
루프를 사용하여 커서에 있는 문서를 반복할 수 있습니다.
foreach ($results as $doc) { echo json_encode($doc), PHP_EOL; }
{"_id":{"$oid":"..."},"name":"Mitsubishi Motors","permalink":"mitsubishi-motors", "crunchbase_url":"http:\/\/www.crunchbase.com\/company\/mitsubishi-motors", ... } {"_id":{"$oid":"..."},"name":"Western Digital","permalink":"western-digital", "crunchbase_url":"http:\/\/www.crunchbase.com\/company\/western-digital", ... } {"_id":{"$oid":"..."},"name":"Celarayn","permalink":"celarayn","crunchbase_url": "http:\/\/www.crunchbase.com\/company\/celarayn", ... }
참고
모든 문서 찾기
컬렉션의 모든 문서를 찾으려면 find()
메서드에 빈 필터를 전달합니다.
$cursor = $collection->find([]);
검색 동작 수정
옵션 값을 매개 변수로 지정하는 배열 을 전달하여 MongoDB\Collection::find()
및 MongoDB\Collection::findOne()
메서드의 동작을 수정할 수 있습니다. 다음 표에서는 배열 에서 설정하다 수 있는 몇 가지 옵션을 설명합니다.
옵션 | 설명 |
---|---|
| The maximum number of documents within each batch returned in a query result. By default,
the find command has an initial batch size of 101 documents
and a maximum size of 16 mebibytes (MiB) for each subsequent batch. This
option can enforce a smaller limit than 16 MiB, but not a larger
one. If you set batchSize to a limit that results in batches larger than
16 MiB, this option has no effect.Type: integer |
| The collation to use for the operation. The default value is the collation
specified for the collection. To learn more, see the Collation
section of this page. Type: array|object |
| The comment to attach to the operation. Type: any BSON type |
| The type of cursor to use for the operation. The default value is
MongoDB\Operation\Find::NON_TAILABLE .Type: MongoDB\Operation\Find |
| The maximum number of documents the operation can return. Type: integer |
| The number of documents to skip before returning results. Type: integer |
| The order in which the operation returns matching documents. Type: array|object |
| The type map to apply to cursors, which determines how BSON documents
are converted to PHP values. The default value is the collection's type map. Type: array |
다음 예시 에서는 find()
메서드를 사용하여 number_of_employees
필드 에 1000
값이 있는 모든 문서를 찾습니다. 이 예시 에서는 limit
옵션을 사용하여 최대 5
결과를 반환합니다.
$results = $collection->find( ['number_of_employees' => 1000], ['limit' => 5], ); foreach ($results as $doc) { echo json_encode($doc), PHP_EOL; }
전체 옵션 목록은 findOne() 및 find() 매개변수에 대한 API 설명서를 참조하세요.
데이터 정렬
작업에 대한 데이터 정렬을 지정하려면 collation
옵션을 설정하는 $options
배열 매개변수를 작업 메서드에 전달합니다. 데이터 정렬 규칙을 구성하는 배열 에 collation
옵션을 할당합니다.
다음 표에서는 데이터 정렬을 구성하기 위해 설정하다 수 있는 필드에 대해 설명합니다.
필드 | 설명 |
---|---|
| (Required) Specifies the International Components for Unicode (ICU) locale. For a
list of supported locales, see Collation Locales and Default Parameters
in the MongoDB Server manual. Data Type: string |
| (Optional) Specifies whether to include case comparison. When set to true , the comparison behavior depends on the value of
the strength field:- If strength is 1 , the PHP library compares basecharacters and case. - If strength is 2 , the PHP library compares basecharacters, diacritics, other secondary differences, and case. - If strength is any other value, this field is ignored.When set to false , the PHP library doesn't include case comparison at
strength level 1 or 2 .Data Type: bool Default: false |
| (Optional) Specifies the sort order of case differences during tertiary
level comparisons. Data Type: string Default: "off" |
| (Optional) Specifies the level of comparison to perform, as defined in the
ICU documentation. Data Type: int Default: 3 |
| (Optional) Specifies whether the driver compares numeric strings as numbers. If set to true , the PHP library compares numeric strings as numbers.
For example, when comparing the strings "10" and "2", the library uses the
strings' numeric values and treats "10" as greater than "2".If set to false , the PHP library compares numeric strings
as strings. For example, when comparing the strings "10" and "2", the library
compares one character at a time and treats "10" as less than "2".For more information, see Collation Restrictions
in the MongoDB Server manual. Data Type: bool Default: false |
| (Optional) Specifies whether the library considers whitespace and punctuation as base
characters for comparison purposes. Data Type: string Default: "non-ignorable" |
| (Optional) Specifies which characters the library considers ignorable when
the alternate field is set to "shifted" .Data Type: string Default: "punct" |
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. Data Type: bool Default: false |
데이터 정렬 및 각 필드에 사용할 수 있는 값에 대해 자세히 학습하려면 MongoDB Server 매뉴얼의 데이터 정렬 항목을 참조하세요.
추가 정보
쿼리 필터에 학습 보려면 쿼리 지정 가이드 를 참조하세요.
API 문서
이 가이드에서 설명하는 메서드에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.