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

문서 교체

이 페이지의 내용

  • 개요
  • 샘플 데이터
  • 대체 작업
  • 필수 매개변수
  • 반환 값
  • 예제
  • 바꾸기 작업 수정
  • 예제
  • 추가 정보
  • API 문서

이 가이드 에서는 MongoDB PHP 라이브러리를 사용하여 MongoDB 컬렉션 에서 대체 작업을 실행 하는 방법을 학습 수 있습니다. 바꾸기 작업은 업데이트 작업과 다르게 수행됩니다. 업데이트 작업은 대상 문서 에서 지정된 필드만 수정합니다. 바꾸기 작업은 대상 문서 의 모든 필드를 제거하고 새 필드로 바꿉니다.

문서 를 바꾸려면 MongoDB\Collection::replaceOne() 메서드를 사용합니다.

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

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

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

MongoDB\Collection::replaceOne() 을(를) 사용하여 바꾸기 작업을 수행할 수 있습니다. 이 메서드는 검색 기준과 일치하는 첫 번째 문서 에서 _id 필드 를 제외한 모든 필드를 제거합니다. 그런 다음 지정한 필드와 값이 문서 에 삽입됩니다.

replaceOne() 메서드에는 다음 매개 변수가 필요합니다.

  • 쿼리 필터하다 문서 대체할 문서를 결정합니다. 쿼리 필터에 대한 자세한 내용은 MongoDB Server 매뉴얼의 필터 문서 쿼리 섹션 을 참조하세요.

  • 문서 바꾸기 는 새 문서에 삽입할 필드와 값을 지정합니다.

replaceOne() 메서드는 MongoDB\UpdateResult 객체 를 반환합니다. 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.
getUpsertedCount()
Returns the number of documents upserted into the database, if any.
getUpsertedId()
Returns the ID of the document that was upserted in the database, if the driver performed an upsert.
isAcknowledged()
Returns a boolean indicating whether the write operation was acknowledged.

다음 예시 에서는 replaceOne() 메서드를 사용하여 name 필드 값이 'Pizza Town' 인 문서 의 필드와 값을 바꿉니다. 그런 다음 수정된 문서 수를 출력합니다.

$replace_document = [
'name' => 'Mongo\'s Pizza',
'cuisine' => 'Pizza',
'address' => [
'street' => '123 Pizza St',
'zipCode' => '10003',
],
'borough' => 'Manhattan'
];
$result = $collection->replaceOne(['name' => 'Pizza Town'], $replace_document);
echo 'Modified documents: ', $result->getModifiedCount();

중요

_id 필드의 값은 변경할 수 없습니다. 대체 문서에서 _id 필드 값을 지정하는 경우 기존 문서의 _id 값과 일치해야 합니다.

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

옵션
설명
upsert
Specifies whether the replace 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 replace operation bypasses document validation. This lets you replace 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.
hint
Gets or sets the index to scan for documents. For more information, see the hint statement in the MongoDB Server manual.
session
Specifies the client session to associate with the operation.
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
Attaches a comment to the operation. For more information, see the insert command fields guide in the MongoDB Server manual.

다음 코드는 replaceOne() 메서드를 사용하여 name 필드 값이 'Food Town' 인 첫 번째 문서 를 찾은 다음 이 문서 를 name 값이 'Food World' 인 새 문서 로 바꿉니다. upsert 옵션이 true 로 설정하다 되어 있으므로 쿼리 필터하다 가 기존 문서와 일치하지 않는 경우 라이브러리는 새 문서 를 삽입합니다.

$replace_document = [
'name' => 'Food World',
'cuisine' => 'Mixed',
'address' => [
'street' => '123 Food St',
'zipCode' => '10003',
],
'borough' => 'Manhattan'
];
$result = $collection->replaceOne(
['name' => 'Food Town'],
$replace_document,
['upsert' => true]
);

업데이트 작업에 대해 자세히 알아보려면 문서 업데이트 가이드를 참조하세요.

쿼리 필터 생성에 대해 자세히 알아보려면 쿼리 지정 가이드를 참조하세요.

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

돌아가기

문서 삭제