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

문서 업데이트

이 페이지의 내용

  • 개요
  • 샘플 데이터
  • 업데이트 작업
  • 하나의 문서 업데이트
  • 다수 문서 업데이트
  • 업데이트 작업 사용자 지정
  • 반환 값
  • 추가 정보
  • API 문서

이 가이드 에서는 MongoDB PHP 라이브러리를 사용하여 MongoDB 컬렉션 의 문서를 업데이트 하는 방법을 학습 수 있습니다. MongoDB\Collection::updateOne() 메서드를 호출하여 단일 문서 를 업데이트 하거나 MongoDB\Collection::updateMany() 메서드를 호출하여 여러 문서를 업데이트 할 수 있습니다.

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

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

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

다음 방법을 사용하여 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() 메서드의 동작을 수정할 수 있습니다. 다음 표에서는 배열 에서 설정하다 수 있는 몇 가지 옵션을 설명합니다.

옵션
설명
upsert
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.
Defaults to false.
bypassDocumentValidation
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.
Defaults to false.
collation
Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.
arrayFilters
Specifies which array elements an update applies to if the operation modifies array fields.
hint
Sets the index to scan for documents. For more information, see the hint statement in the MongoDB Server manual.
writeConcern
Sets the write concern for the operation. For more information, see Write Concern 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.
comment
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]
);

updateOne()updateMany() 메서드는 MongoDB\UpdateResult 클래스의 인스턴스 를 반환합니다. 이 클래스에는 다음과 같은 멤버 함수가 포함되어 있습니다.

기능
설명
getMatchedCount()
Returns the number of documents that matched the query filter, regardless of how many were updated.
getModifiedCount()
Returns the number of documents modified by the update operation. If an updated document is identical to the original, it is not included in this count.
isAcknowledged()
Returns a boolean indicating whether the write operation was acknowledged.
getUpsertedCount()
Returns the number of document that were upserted into the database.
getUpsertedId()
Returns the ID of the document that was upserted in the database, if the driver performed an upsert.

다음 예시 에서는 updateMany() 메서드를 사용하여 일치하는 문서의 name 필드 를 'Dunkin' Donuts' 에서 'Dunkin'' 로 업데이트 합니다. getModifiedCount() 멤버 함수를 호출하여 수정된 문서 수를 출력합니다.

$result = $collection->updateMany(
['name' => 'Dunkin\' Donuts'],
['$set' => ['name' => 'Dunkin\'']]
);
echo 'Modified documents: ', $result->getModifiedCount();

쿼리 필터 만들기에 학습 보려면 쿼리 지정 가이드 를 참조하세요.

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

돌아가기

MongoDB에 데이터 쓰기