Docs Menu
Docs Home
/ / /
PHP 라이브러리 매뉴얼
/

문서 삭제

이 가이드 에서는 삭제 작업 을 수행하여 MongoDB PHP 라이브러리를 사용하여 MongoDB 컬렉션 에서 문서를 제거 하는 방법을 학습 수 있습니다.

삭제 작업은 MongoDB 컬렉션에서 하나 이상의 문서를 제거합니다. MongoDB\Collection::deleteOne() 또는 MongoDB\Collection::deleteMany() 메서드를 사용하여 삭제 작업을 수행할 수 있습니다.

이 가이드 의 예제에서는 Atlas 샘플 데이터 세트sample_restaurants 데이터베이스 에 있는 restaurants 컬렉션 을 사용합니다. PHP 애플리케이션 에서 이 컬렉션 에 액세스 하려면 Atlas cluster 에 연결하는 MongoDB\Client 를 인스턴스화하고 $collection 변수에 다음 값을 할당합니다.

$collection = $client->sample_restaurants->restaurants;

무료 MongoDB Atlas cluster 를 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 보려면 Atlas 시작하기 가이드 를 참조하세요.

다음 방법을 사용하여 삭제 작업을 수행할 수 있습니다.

  • MongoDB\Collection::deleteOne()Atlas Search 기준과 일치 하는 첫 번째 문서를 삭제합니다.

  • MongoDB\Collection::deleteMany()Atlas Search 기준과 일치하는 모든 문서 를 삭제합니다.

각 삭제 메서드에는 제거할 문서를 결정하기 위한 검색 기준을 지정하는 쿼리 필터하다 문서 가 필요합니다. 쿼리 필터에 대한 자세한 내용은 MongoDB Server 매뉴얼의 필터 문서 쿼리 섹션 을 참조하세요.

다음 예시 에서는 deleteOne() 메서드를 사용하여 restaurants 컬렉션 에서 name 값이 'Ready Penny Inn' 인 문서 를 제거 합니다.

$collection->deleteOne(['name' => 'Ready Penny Inn']);

다음 예시 에서는 deleteMany() 메서드를 사용하여 restaurants 컬렉션 에서 borough 값이 'Brooklyn' 인 모든 문서를 제거 합니다.

$collection->deleteMany(['borough' => 'Brooklyn']);

옵션 값을 매개 변수로 지정하는 배열 을 전달하여 MongoDB\Collection::deleteOne()MongoDB\Collection::deleteMany() 메서드의 동작을 수정할 수 있습니다. 다음 표에서는 배열 에서 설정하다 수 있는 옵션에 대해 설명합니다.

옵션
설명

collation

Specifies the kind of language collation to use when comparing strings. To learn more, see the Collation section of this page.

writeConcern

Sets the write concern for the operation. This option defaults to the collection's write concern. For more information, see Write Concern in the MongoDB Server manual.

hint

Gets or sets the index to scan for documents. For more information, see the hint statement in the MongoDB Server manual.

let

Specifies a document with a list of values to improve operation readability. Values must be constant or closed expressions that don't reference document fields. For more information, see the let statement in the MongoDB Server manual.

session

Specifies the client session to associate with the operation. For more information, see Session in the MongoDB Server manual.

comment

Attaches a comment to the operation. For more information, see the delete command fields guide in the MongoDB Server manual.

작업에 대한 데이터 정렬을 지정하려면 collation 옵션을 설정하는 $options 배열 매개변수를 작업 메서드에 전달합니다. 데이터 정렬 규칙을 구성하는 배열 에 collation 옵션을 할당합니다.

다음 표에서는 데이터 정렬을 구성하기 위해 설정하다 수 있는 필드에 대해 설명합니다.

필드
설명

locale

(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

caseLevel

(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 base
characters and case.

- If strength is 2, the PHP library compares base
characters, 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

caseFirst

(Optional) Specifies the sort order of case differences during tertiary level comparisons.

Data Type: string
Default: "off"

strength


Data Type: int
Default: 3

numericOrdering

(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

alternate

(Optional) Specifies whether the library considers whitespace and punctuation as base characters for comparison purposes.

Data Type: string
Default: "non-ignorable"

maxVariable

(Optional) Specifies which characters the library considers ignorable when the alternate field is set to "shifted".

Data Type: string
Default: "punct"

backwards

(Optional) Specifies whether strings containing diacritics sort from the back of the string to the front.

Data Type: bool
Default: false

데이터 정렬 및 각 필드 에 사용할 수 있는 값에 대해 자세히 학습 MongoDB Server 매뉴얼의 데이터 정렬 항목을 참조하세요.

다음 예시 에서는 deleteMany() 메서드를 호출하여 restaurants 컬렉션 에서 'Mongo' string 이 포함된 name 값이 있는 모든 문서를 삭제 합니다. 또한 배열 매개변수에 comment 옵션을 설정하여 작업에 주석을 추가합니다.

$collection->deleteMany(
['name' => new MongoDB\BSON\Regex('Mongo')],
['comment' => 'Deleting Mongo restaurants'],
);

참고

앞의 예시 에서 deleteMany() 메서드를 deleteOne() 로 바꾸면 라이브러리는 'Mongo' 을 포함하는 name 값이 있는 첫 번째 문서 만 삭제합니다.

MongoDB\Collection::deleteOne()MongoDB\Collection::deleteMany() 메서드는 MongoDB\DeleteResult 객체 를 반환합니다. 이 클래스에는 다음과 같은 멤버 함수가 포함되어 있습니다.

  • isAcknowledged()는 작업이 승인되었는지 여부를 나타내는 부울을 반환합니다.

  • getDeletedCount(), 삭제된 문서 수를 반환합니다. 쓰기 (write) 작업이 승인되지 않은 경우 이 메서드는 오류를 발생시킵니다.

쿼리 필터하다 가 어떤 문서와도 일치하지 않으면 운전자 는 어떤 문서도 삭제 하지 않고 getDeletedCount()0 을 반환합니다.

다음 예시 에서는 deleteMany() 메서드를 호출하여 cuisine 값이 'Greek' 인 문서를 삭제 합니다. 그런 다음 getDeletedCount() 멤버 함수를 호출하여 삭제된 문서 수를 출력합니다.

$result = $collection->deleteMany(['cuisine' => 'Greek']);
echo 'Deleted documents: ', $result->getDeletedCount(), PHP_EOL;
Deleted documents: 111

이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.

돌아가기

문서 교체

이 페이지의 내용