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

대량 쓰기 작업

이 가이드 에서는 대량 쓰기 (write) 작업 을 사용하여 단일 데이터베이스 호출에서 여러 쓰기 (write) 작업을 수행하는 방법에 학습 설명합니다.

문서 삽입하고, 다른 여러 문서를 업데이트 다음, 문서 삭제 하려는 시나리오를 가정해 보겠습니다. 개별 메서드를 사용하는 경우 각 작업에는 자체 데이터베이스 호출이 필요합니다.

대량 쓰기 (write) 작업을 사용하면 더 적은 수의 데이터베이스 호출로 여러 쓰기 (write) 작업을 수행할 수 있습니다. 다음 수준에서 대량 쓰기 (write) 작업을 수행할 수 있습니다.

  • 클라이언트: 애플리케이션 MongoDB Server 버전 8.0 이상에 연결되는 경우 MongoDB\Client::bulkWrite() 메서드를 사용하여 동일한 클러스터 에 있는 여러 컬렉션 및 데이터베이스에서 대량 쓰기 (write) 작업을 수행할 수 있습니다. 이 메서드는 한 번의 데이터베이스 호출로 모든 쓰기 (write) 작업을 수행합니다. 이 기능에 대해 자세히 학습 보려면 Mongo.bulkWrite() MongoDB Server 매뉴얼의 참조입니다.

  • 컬렉션: MongoDB\Collection::bulkWrite() 메서드를 사용하여 단일 컬렉션에 대해 대량 쓰기 (write) 작업을 수행할 수 있습니다. 이 메서드는 각 유형의 쓰기 (write) 작업에 대해 데이터베이스 호출합니다. 예시 를 들어 메서드는 한 번의 호출로 여러 업데이트 작업을 수행할 수 있지만 삽입 작업과 바꾸기 작업에 대해 데이터베이스 두 번 개별적으로 호출합니다.

이 가이드 의 예제에서는 Atlas 샘플 데이터 세트의 및 컬렉션을 사용합니다.sample_restaurants.restaurants sample_mflix.movies 무료 MongoDB Atlas cluster 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 Atlas 시작하기 가이드 참조하세요.

PHP 라이브러리 v2.1 를 사용하고 MongoDB Server 8.0 이상을 실행 배포서버에 연결할 때 MongoDB\Client::bulkWrite() 메서드를 사용하여 동일한 클러스터의 여러 데이터베이스 및 컬렉션에 쓰기 (write) 수 있습니다. 이 메서드는 한 번의 호출로 모든 쓰기 (write) 작업을 수행합니다.

먼저,MongoDB\ClientBulkWrite 빌더를 사용하여 수행할 쓰기 (write) 작업을 지정하는 BulkWriteCommand 인스턴스 만듭니다. 다음 코드는 createWithCollection() 메서드를 사용하여 MongoDB\Collection 인스턴스 에서 ClientBulkWrite 인스턴스 만드는 방법을 보여 줍니다.

$restaurantCollection = $client->sample_restaurants->restaurants;
$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection);

그런 다음 ClientBulkWrite 인스턴스 에서 다음 쓰기 (write) 메서드 중 하나 이상을 호출하여 대량 쓰기 (write) 작업을 구성합니다.

  • deleteOne()

  • deleteMany()

  • insertOne()

  • replaceOne()

  • updateOne()

  • updateMany()

후속 쓰기 (write) 작업을 위해 다른 네임스페이스 선택하려면 다음 코드에 표시된 대로 ClientBulkWrite 인스턴스 에서 withCollection() 메서드를 호출합니다.

$movieCollection = $client->sample_mflix->movies;
$bulkWrite = $bulkWrite->withCollection($movieCollection);

다음 섹션에서는 ClientBulkWrite 클래스를 만들고 사용하여 대량 쓰기 (write) 에서 쓰기 (write) 작업을 지정하는 방법을 보여 줍니다. 대량 작업 수행 섹션에서는 ClientBulkWrite 객체 bulkWrite() 메서드에 전달하여 대량 작업을 수행하는 방법을 보여 줍니다.

삽입 작업을 지정하려면 ClientBulkWrite 인스턴스 에서 insertOne() 메서드를 호출합니다.

다음 예시 에서는 sample_restaurants.restaurantssample_mflix.movies 컬렉션에 문서를 삽입하는 방법을 지정합니다.

$restaurantCollection = $client->sample_restaurants->restaurants;
$movieCollection = $client->sample_mflix->movies;
$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection);
$bulkWrite->insertOne(['name' => 'Mongo Deli', 'cuisine' => 'Sandwiches']);
$bulkWrite = $bulkWrite->withCollection($movieCollection);
$bulkWrite->insertOne(['title' => 'The Green Ray', 'year' => 1986]);

일치하는 첫 번째 문서 에 대한 업데이트 작업을 지정하려면 ClientBulkWrite 인스턴스 에서 updateOne() 메서드를 호출합니다.

다음 예시 에서는 sample_restaurants.restaurants 컬렉션 에서 name 값이 'Dandelion Bakery'인 첫 번째 문서 에 대한 $set 업데이트 지정합니다.

$restaurantCollection = $client->sample_restaurants->restaurants;
$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection);
$bulkWrite->updateOne(
['name' => 'Dandelion Bakery'],
['$set' => ['grade' => 'B+']],
['upsert' => true],
);

여러 문서를 업데이트 하려면 updateMany() 메서드를 호출합니다. 지정된 작업은 쿼리 필터하다 와 일치하는 모든 문서 를 업데이트합니다.

다음 예시 name 값이 'Starbucks'sample_restaurants.restaurants 컬렉션 에서 일치하는 모든 문서에 $set 업데이트 지정합니다.

$restaurantCollection = $client->sample_restaurants->restaurants;
$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection);
$bulkWrite->updateMany(
['name' => 'Starbucks'],
['$set' => ['cuisine' => 'Coffee (Chain)']],
);

일치하는 첫 번째 문서 에 대체 작업을 지정하려면 ClientBulkWrite 인스턴스 에서 replaceOne() 메서드를 호출합니다.

다음 예시 name 값이 'Dandelion Bakery'sample_restaurants.restaurants 컬렉션 의 첫 번째 문서 에 대한 바꾸기 작업을 지정합니다.

$restaurantCollection = $client->sample_restaurants->restaurants;
$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection);
$bulkWrite->replaceOne(
['name' => 'Dandelion Bakery'],
['name' => 'Flower Patisserie', 'cuisine' => 'Bakery & Cafe'],
);

일치하는 첫 번째 문서 에 대한 삭제 작업을 지정하려면 ClientBulkWrite 인스턴스 에서 deleteOne() 메서드를 호출합니다.

다음 예시 에서는 sample_restaurants.restaurants 컬렉션 에서 borough 값이 'Queens'인 첫 번째 문서 를 삭제하도록 지정합니다.

$restaurantCollection = $client->sample_restaurants->restaurants;
$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection);
$bulkWrite->deleteOne(
['borough' => 'Queens'],
);

여러 문서를 삭제 하려면 deleteMany() 메서드를 호출합니다. 지정된 작업은 쿼리 필터하다 와 일치하는 모든 문서 를 삭제합니다.

다음 예시 에서는 sample_restaurants.restaurants 컬렉션 에서 두 개의 연속적인 'p' 문자가 포함된 name 값을 가진 모든 문서를 삭제하도록 지정합니다.

$restaurantCollection = $client->sample_restaurants->restaurants;
$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection);
$bulkWrite->deleteMany(
['name' => ['$regex' => 'p{2,}']],
);

쓰기 (write) 작업을 지정하기 위해 ClientBulkWrite 인스턴스 구성한 후 이를 MongoDB\Client::bulkWrite() 메서드에 전달합니다. 기본값 으로 이러한 메서드는 ClientBulkWrite 구성 시 정의한 순서대로 작업을 실행 .

다음 코드는 bulkWrite() 메서드를 사용하여 여러 네임스페이스에서 대량 쓰기 (write) 작업을 수행하는 방법을 보여 줍니다.

$restaurantCollection = $client->sample_restaurants->restaurants;
$movieCollection = $client->sample_mflix->movies;
// Creates the bulk write command and sets the target namespace.
$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection($restaurantCollection);
// Specifies insertion of one document.
$bulkWrite->insertOne(['name' => 'Mongo Deli', 'cuisine' => 'Sandwiches']);
// Specifies a `$set` update to one document with the upsert option
// enabled.
$bulkWrite->updateOne(
['name' => 'Dandelion Bakery'],
['$set' => ['grade' => 'B+']],
['upsert' => true],
);
// Changes the target namespace.
$bulkWrite = $bulkWrite->withCollection($movieCollection);
// Specifies insertion of one document.
$bulkWrite->insertOne(['title' => 'The Green Ray', 'year' => 1986]);
// Specifies deletion of documents in which `title` has two consective
// 'd' characters.
$bulkWrite->deleteMany(
['title' => ['$regex' => 'd{2,}']],
);
// Specifies replacement of one document.
$bulkWrite->replaceOne(
['runtime' => ['$gte' => 200]],
['title' => 'Seven Samurai', 'runtime' => 203],
);
// Performs the bulk write operation.
$result = $client->bulkWrite($bulkWrite);
// Prints a summary of results.
echo 'Inserted documents: ', $result->getInsertedCount(), PHP_EOL;
echo 'Modified documents: ', $result->getModifiedCount(), PHP_EOL;
echo 'Deleted documents: ', $result->getDeletedCount(), PHP_EOL;
Inserted documents: 2
Modified documents: 2
Deleted documents: 200

옵션 값을 매개 변수로 지정하는 ClientBulkWrite 생성자에 배열 전달하여 클라이언트 대량 쓰기 (write) 작업의 동작을 수정할 수 있습니다. 다음 표에서는 배열 에서 설정하다 수 있는 옵션에 대해 설명합니다.

옵션
설명

bypassDocumentValidation

Specifies whether the operation bypasses document validation. This lets you modify 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.
The default is false.

comment

Attaches a comment to the operation. For more information, see the insert command fields guide 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.

ordered

If set to true: When a single write fails, the operation stops without performing the remaining writes and throws an exception.
If set to false: When a single write fails, the operation continues to attempt the remaining write operations, if any, then throws an exception.
The default is true.

verboseResults

Specifies whether to return verbose results.
The default is false.

다음 예시 ClientBulkWrite 인스턴스 만들고 ordered 옵션을 false로 설정합니다.

$bulkWrite = MongoDB\ClientBulkWrite::createWithCollection(
$restaurantCollection,
['ordered' => false]
);

참고

순서가 지정되지 않은 동작

순서가 지정되지 않은 대량 작업은 실행 순서를 보장하지 않습니다. 순서는 런타임을 최적화하기 위해 나열하는 방식과 다를 수 있습니다. 순서가 지정되지 않은 대량 쓰기 (write) 에서 다음과 같은 쓰기 (write) 작업을 지정한다고 가정해 보겠습니다.

$bulkWrite->insertOne(['_id' => 4045, 'title' => 'The Green Ray']);
$bulkWrite->deleteOne(['_id' => 4045]);

라이브러리에서 두 작업 중 하나를 먼저 실행 수 있으므로 결과에는 삭제된 문서 하나가 표시되거나 삭제된 문서가 표시되지 않을 수 있습니다.

bulkWrite() 메서드를 호출할 때 옵션을 전달하여 작업에 사용할 클라이언트 세션 또는 쓰기 고려 (write concern) 지정할 수도 있습니다.

MongoDB\Client::bulkWrite() 메서드는 MongoDB\BulkWriteCommandResult 객체 반환합니다. 이 클래스에는 다음 메서드가 포함되어 있습니다.

메서드
설명

getInsertedCount()

Returns the total number of documents inserted by all insert operations in the bulk write command.

getMatchedCount()

Returns the total number of documents matched by all update and replace operations in the bulk write command.

getModifiedCount()

Returns the total number of documents modified by all update and replace operations in the bulk write command.

getUpsertedCount()

Returns the total number of documents upserted by all update and replace operations in the bulk write command.

getDeletedCount()

Return the total number of documents deleted by all delete operations in the bulk write command.

getInsertResults()

Returns a map of results of each successful insert operation. Each operation is represented by an integer key, which contains a document with information corresponding to the operation such as the inserted _id value.

getUpdateResults()

Returns a map of results of each successful update operation. Each operation is represented by an integer key, which contains a document with information corresponding to the operation.

getDeleteResults()

Returns a map of results of each successful delete operation. Each operation is represented by an integer key, which contains a document with information corresponding to the operation.

isAcknowledged()

Returns a boolean indicating whether the server acknowledged the bulk operation.

대량 쓰기 (write) 작업을 실행 하려면 쓰기 (write) 작업 배열을 MongoDB\Collection::bulkWrite() 메서드에 전달합니다. 쓰기 (write) 작업을 지정하려면 다음 구문을 사용합니다.

[
[ 'deleteMany' => [ $filter ] ],
[ 'deleteOne' => [ $filter ] ],
[ 'insertOne' => [ $document ] ],
[ 'replaceOne' => [ $filter, $replacement, $options ] ],
[ 'updateMany' => [ $filter, $update, $options ] ],
[ 'updateOne' => [ $filter, $update, $options ] ],
]

삭제, 삽입, 대체 및 업데이트 작업에 대해 자세히 학습하려면 MongoDB 에 데이터 쓰기 섹션의 가이드를 참조하세요.

bulkWrite() 메서드를 호출하면 라이브러리는 배열 에 지정한 순서대로 쓰기 (write) 작업을 자동으로 실행합니다. 쓰기 (write) 작업을 임의의 순서로 실행 하도록 bulkWrite() 에 지시하는 방법을 학습 대량 쓰기 작업 사용자 지정 섹션을 참조하세요.

이 예시 에서는 restaurants 컬렉션 에서 다음 쓰기 (write) 작업을 실행합니다.

  • name 값이 'Mongo's Deli'인 문서 를 삽입하는 삽입 작업

  • name 값이 'Mongo's Deli'인 문서 의 cuisine 필드 를 업데이트 하는 업데이트 작업 입니다.

  • borough 값이 'Manhattan'인 모든 문서를 삭제 하는 삭제 작업 입니다.

$restaurantCollection = $client->sample_restaurants->restaurants;
$result = $restaurantCollection->bulkWrite(
[
[
'insertOne' => [
['name' => 'Mongo\'s Deli'],
['cuisine' => 'Sandwiches'],
['borough' => 'Manhattan'],
['restaurant_id' => '1234'],
],
],
[
'updateOne' => [
['name' => 'Mongo\'s Deli'],
['$set' => ['cuisine' => 'Sandwiches and Salads']],
],
],
[
'deleteMany' => [
['borough' => 'Manhattan'],
],
],
]
);

참고

라이브러리가 대량 작업을 실행할 때 대상 컬렉션 의 쓰기 고려 (write concern) 사용합니다. 운전자 실행 순서에 관계없이 모든 작업을 시도한 후 모든 쓰기 고려 (write concern) 오류를 보고합니다.

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

옵션
설명

bypassDocumentValidation

Specifies whether the operation bypasses document validation. This lets you modify 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.
The default is false.

codec

Sets the codec to use for encoding or decoding documents. Bulk writes use the codec for insertOne() and replaceOne() operations. For more information, see the Codecs guide.

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.

ordered

If set to true: When a single write fails, the operation stops without performing the remaining writes and throws an exception.
If set to false: When a single write fails, the operation continues to attempt the remaining write operations, if any, then throws an exception.
The default is true.

comment

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

session

Specifies the client session to associate with the operation.

다음 예시 에서는 bulkWrite() 메서드를 호출하여 삽입 및 삭제 작업을 수행하고 ordered 옵션을 false 로 설정합니다.

$result = $restaurantCollection->bulkWrite(
[
[
'insertOne' => [
['name' => 'Mongo\'s Pizza'],
['cuisine' => 'Italian'],
['borough' => 'Queens'],
['restaurant_id' => '5678'],
],
],
[
'deleteOne' => [
['restaurant_id' => '5678'],
],
],
],
['ordered' => false]
);

라이브러리가 삽입 작업을 먼저 실행하면 문서 하나가 삭제됩니다. 삭제 작업을 먼저 실행하면 문서가 삭제되지 않습니다.

참고

순서가 지정되지 않은 동작

순서가 지정되지 않은 대량 작업은 실행 순서가 보장되지 않습니다. 이 순서는 런타임을 최적화하기 위해 나열한 방식과 다를 수 있습니다.

MongoDB\Collection::bulkWrite() 메서드는 MongoDB\BulkWriteResult 객체 반환합니다. 이 클래스에는 다음 메서드가 포함되어 있습니다.

메서드
설명

getInsertedCount()

Returns the total number of documents inserted by all insert operations in the bulk write command.

getInsertedIds()

Returns a map of _id field values for documents inserted by all insert operations in the bulk write command.

getMatchedCount()

Returns the total number of documents matched by all update and replace operations in the bulk write command.

getModifiedCount()

Returns the total number of documents modified by all update and replace operations in the bulk write command.

getUpsertedCount()

Returns the total number of documents upserted by all update and replace operations in the bulk write command.

getUpsertedIds()

Returns a map of _id field values for documents upserted by all update and replace operations in the bulk write command.

getDeletedCount()

Return the total number of documents deleted by all delete operations in the bulk write command.

isAcknowledged()

Returns a boolean indicating whether the server acknowledged the bulk operation.

개별 쓰기 작업을 수행하는 방법을 알아보려면 다음 가이드를 참조하세요.

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

돌아가기

바꾸기

이 페이지의 내용