개요
이 가이드 에서는 MongoDB PHP 라이브러리를 사용하여 MongoDB 컬렉션 의 문서를 업데이트 하는 방법을 학습 수 있습니다. MongoDB\Collection::updateOne() 메서드를 호출하여 단일 문서 를 업데이트 하거나 MongoDB\Collection::updateMany() 메서드를 호출하여 여러 문서를 업데이트 할 수 있습니다.
샘플 데이터
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에서 업데이트 작업을 수행할 수 있습니다.
MongoDB\Collection::updateOne()검색 조건과 일치하는 첫 번째 문서가 업데이트됩니다.MongoDB\Collection::updateMany()검색 조건과 일치하는 모든 문서가 업데이트됩니다.
각 업데이트 방법에는 다음 매개변수가 필요합니다.
쿼리 필터하다 문서: 업데이트 할 문서를 지정합니다. 쿼리 필터에 대한 자세한 내용은 MongoDB Server 매뉴얼의 필터 문서 쿼리 섹션 을 참조하세요.
문서 업데이트:업데이트 연산자 또는 수행할 업데이트 의 종류, 변경할 필드 및 값을 지정합니다. 업데이트 연산자 목록 및 사용법은 MongoDB Server 매뉴얼의 필드 업데이트 연산자 가이드 참조하세요.
하나의 문서 업데이트
다음 예시 에서는 updateOne() 메서드를 사용하여 restaurants 컬렉션 에 있는 문서 의 name 값을 'Bagels N Buns' 에서 '2 Bagels 2 Buns' 로 업데이트 합니다.
$result = $collection->updateOne( ['name' => 'Bagels N Buns'], ['$set' => ['name' => '2 Bagels 2 Buns']], );
다수 문서 업데이트
다음 예시 에서는 updateMany() 메서드를 사용하여 cuisine 값이 'Pizza' 인 모든 문서를 업데이트 합니다. 업데이트 후 문서의 cuisine 값은 'Pasta' 입니다.
$result = $collection->updateMany( ['cuisine' => 'Pizza'], ['$set' => ['cuisine' => 'Pasta']], );
업데이트 작업 사용자 지정
옵션 값을 매개 변수로 지정하는 배열 을 전달하여 updateOne() 및 updateMany() 메서드의 동작을 수정할 수 있습니다. 다음 표에서는 배열 에서 설정하다 수 있는 몇 가지 옵션을 설명합니다.
옵션 | 설명 |
|---|---|
| Specifies whether the update operation performs an upsert operation if no documents match the query filter. For more information, see the upsert statement in the MongoDB Server manual. |
| Specifies whether the update operation bypasses document validation. This lets you update documents that don't meet the schema validation requirements, if any exist. For more information about schema validation, see Schema Validation in the MongoDB Server manual. |
|
|
| Specifies the kind of language collation to use when sorting results. To learn more, see the Collation section of this page. |
| 작업이 배열 필드를 수정하는 경우 업데이트 를 적용할 배열 요소를 지정합니다. |
| Sets the index to scan for documents. For more information, see the hint statement in the MongoDB Server manual. |
| Sets the write concern for the operation. For more information, see Write Concern in the MongoDB Server manual. |
| 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. |
| A comment to attach to the operation. For more information, see the insert command fields guide in the MongoDB Server manual. |
다음 예시 에서는 updateMany() 메서드를 사용하여 borough 값이 'Manhattan' 인 모든 문서를 찾습니다. 그런 다음 이러한 문서의 borough 값을 'Manhattan (north)' 로 업데이트합니다. upsert 옵션이 true 로 설정하다 되어 있기 때문에 쿼리 필터하다 가 기존 문서와 일치하지 않는 경우 MongoDB PHP 라이브러리는 새 문서 를 삽입합니다.
$result = $collection->updateMany( ['borough' => 'Manhattan'], ['$set' => ['borough' => 'Manhattan (north)']], ['upsert' => true], );
데이터 정렬
작업에 대한 데이터 정렬을 지정하려면 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. |
| (선택 사항) 대/소문자 비교 포함 여부를 지정합니다. |
| (선택 사항) 3차 수준 비교 시 대소문자 차이의 정렬 순서를 지정합니다. |
| (Optional) Specifies the level of comparison to perform, as defined in the ICU documentation. |
| (선택 사항) 운전자 숫자 문자열을 숫자로 비교할지 여부를 지정합니다. |
| (선택 사항) 비교를 위해 라이브러리에서 공백과 구듁점을 기본 문자로 간주할지 여부를 지정합니다. |
| (선택 사항) |
| (선택 사항) 분음 부호가 포함된 string이 string의 뒤쪽에서 앞쪽으로 정렬되는지 지정합니다. |
데이터 정렬 및 각 필드에 사용할 수 있는 값에 대해 자세히 학습하려면 MongoDB Server 매뉴얼의 데이터 정렬 항목을 참조하세요.
반환 값
updateOne() 및 updateMany() 메서드는 MongoDB\UpdateResult 클래스의 인스턴스 를 반환합니다. 이 클래스에는 다음과 같은 멤버 함수가 포함되어 있습니다.
기능 | 설명 |
|---|---|
| 업데이트된 문서 수에 관계없이 쿼리 필터하다 와 일치하는 문서 수를 반환합니다. |
| 업데이트 작업으로 수정된 문서 수를 반환합니다. 업데이트된 문서 원본과 동일한 경우 이 계산에 포함되지 않습니다. |
| 쓰기 (write) 작업이 승인되었는지 여부를 나타내는 부울을 반환합니다. |
| 데이터베이스 에 업서트된 문서 수를 반환합니다. |
| 운전자 업서트 수행한 경우 데이터베이스 에 업서트된 문서 의 ID 반환합니다. |
다음 예시 에서는 updateMany() 메서드를 사용하여 일치하는 문서의 name 필드 를 'Dunkin' Donuts' 에서 'Dunkin'' 로 업데이트 합니다. getModifiedCount() 멤버 함수를 호출하여 수정된 문서 수를 출력합니다.
$result = $collection->updateMany( ['name' => 'Dunkin\' Donuts'], ['$set' => ['name' => 'Dunkin\'']], ); echo 'Modified documents: ', $result->getModifiedCount();
추가 정보
쿼리 필터 생성에 대해 자세히 알아보려면 쿼리 지정 가이드를 참조하세요.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.