AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

대량 쓰기 작업

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

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

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 C++ application, instantiate a mongocxx::client that connects to an Atlas cluster and assign the following values to your db and collection variables:

auto db = client["sample_restaurants"];
auto collection = db["restaurants"];

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

대량 쓰기 (write) 작업을 실행 하기 전에 컬렉션 에서 create_bulk_write() 메서드를 호출합니다. 이 메서드는 수행할 대량 쓰기 유형에 대한 지침을 저장 하는 데 사용할 수 있는 mongocxx::bulk_write 클래스의 인스턴스 를 반환합니다.

다음 예시 에서는 restaurants 컬렉션 에서 create_bulk_write() 메서드를 호출합니다.

auto bulk = collection.create_bulk_write();

그런 다음 mongocxx::bulk_write 인스턴스 에 쓰기 (write) 모델을 추가하여 대량 작업을 정의할 수 있습니다. 자세한 내용은 다음 쓰기 작업 정의 섹션을 참조하세요.

수행하려는 각 쓰기 (write) 작업에 대해 다음 모델 클래스 중 하나의 인스턴스 를 만듭니다.

  • mongocxx::model::insert_one

  • mongocxx::model::update_one

  • mongocxx::model::update_many

  • mongocxx::model::replace_one

  • mongocxx::model::delete_one

  • mongocxx::model::delete_many

그런 다음 create_bulk_write() 메서드에서 반환된 mongocxx::bulk_write 인스턴스 에 각 쓰기 (write) 모델을 추가합니다.

다음 섹션에서는 이전 쓰기 (write) 모델 클래스의 인스턴스를 만들고 사용하는 방법을 보여줍니다.

삽입 작업을 수행하려면 mongocxx::model::insert_one 클래스의 인스턴스 를 만들고 삽입하려는 문서 를 지정합니다. 그런 다음 모델 인스턴스 를 mongocxx::bulk_write 클래스의 인스턴스 에 추가합니다.

다음 예시 에서는 mongocxx::model::insert_one 인스턴스 를 만들어 bulk mongocxx::bulk_write 인스턴스 에 추가합니다.

auto insert_doc = make_document(kvp("name", "Mongo's Deli"),
kvp("cuisine", "Sandwiches"),
kvp("borough", "Manhattan"),
kvp("restaurant_id", "1234"));
mongocxx::model::insert_one insert_op{insert_doc.view()};
bulk.append(insert_op);

여러 문서를 삽입하려면 각 문서 에 대해 mongocxx::model::insert_one 인스턴스 를 만듭니다.

문서 를 업데이트 하려면 mongocxx::model::update_one 인스턴스 를 만듭니다. 이 모델은 운전자 에 쿼리 필터하다 와 일치 하는 첫 번째 문서 를 업데이트 하도록 지시합니다. 그런 다음 모델 인스턴스 를 mongocxx::bulk_write 클래스의 인스턴스 에 추가합니다.

다음 인수를 mongocxx::model::update_one 모델에 전달합니다.

  • 컬렉션 의 문서를 일치시키는 데 사용되는 기준을 지정하는 쿼리 필터하다 문서 입니다.

  • 수행할 업데이트 의 종류를 지정하는 업데이트 문서 입니다. 업데이트 작업에 대한 자세한 내용은 MongoDB Server 매뉴얼의 필드 업데이트 연산자 가이드 를 참조하세요.

다음 예시 에서는 mongocxx::model::update_one 인스턴스 를 만들어 bulk mongocxx::bulk_write 인스턴스 에 추가합니다.

auto filter_doc = make_document(kvp("name", "Mongo's Deli"));
auto update_doc = make_document(kvp("$set", make_document(kvp("cuisine", "Sandwiches and Salads"))));
mongocxx::model::update_one update_op{filter_doc.view(), update_doc.view()};
bulk.append(update_op);

여러 문서를 업데이트 하려면 mongocxx::model::update_many 인스턴스 를 만들고 동일한 인수를 전달합니다. 이 모델은 운전자 에 쿼리 필터하다 와 일치하는 모든 문서를 업데이트 하도록 지시합니다.

다음 예시 에서는 mongocxx::model::update_many 인스턴스 를 생성하여 bulk 에 추가합니다.

auto filter_doc = make_document(kvp("name", "Mongo's Deli"));
auto update_doc = make_document(kvp("$set", make_document(kvp("cuisine", "Sandwiches and Salads"))));
mongocxx::model::update_many update_op{filter_doc.view(), update_doc.view()};
bulk.append(update_op);

바꾸기 작업은 지정된 문서 의 모든 필드와 값을 제거하고 새 항목으로 바꿉니다. 바꾸기 작업을 수행하려면 mongocxx::model::replace_one 클래스의 인스턴스 를 만들고 쿼리 필터하다 와 일치하는 문서 에 저장 하려는 필드 및 값을 전달합니다. 그런 다음 모델 인스턴스 를 mongocxx::bulk_write 클래스의 인스턴스 에 추가합니다.

다음 예시 에서는 mongocxx::model::replace_one 인스턴스 를 만들어 bulk mongocxx::bulk_write 인스턴스 에 추가합니다.

auto filter_doc = make_document(kvp("restaurant_id", "1234"));
auto replace_doc = make_document(kvp("name", "Mongo's Deli"),
kvp("cuisine", "Sandwiches and Salads"),
kvp("borough", "Brooklyn"),
kvp("restaurant_id", "5678"));
mongocxx::model::replace_one replace_op{filter_doc.view(), replace_doc.view()};
bulk.append(replace_op);

여러 문서를 바꾸려면 각 문서 에 대해 mongocxx::model::replace_one 의 새 인스턴스 를 만들어야 합니다.

문서 를 삭제 하려면 mongocxx::model::delete_one 클래스의 인스턴스 를 만들고 삭제 하려는 문서 를 지정하는 쿼리 필터하다 를 전달합니다. 이 모델은 운전자 에 쿼리 필터하다 와 일치 하는 첫 번째 문서 만 삭제 하도록 지시합니다. 그런 다음 모델 인스턴스 를 mongocxx::bulk_write 클래스의 인스턴스 에 추가합니다.

다음 예시 에서는 mongocxx::model::delete_one 인스턴스 를 만들어 bulk mongocxx::bulk_write 인스턴스 에 추가합니다.

auto filter_doc = make_document(kvp("restaurant_id", "5678"));
mongocxx::model::delete_one delete_op{filter_doc.view()};
bulk.append(delete_op);

여러 문서를 삭제 하려면 mongocxx::model::delete_many 클래스의 인스턴스 를 만들고 삭제 하려는 문서 를 지정하는 쿼리 필터하다 를 전달합니다. 이 모델은 운전자 에 쿼리 필터하다 와 일치하는 모든 문서를 삭제 하도록 지시합니다.

다음 예시 에서는 mongocxx::model::delete_many 인스턴스 를 생성하여 bulk 에 추가합니다.

auto filter_doc = make_document(kvp("borough", "Manhattan"));
mongocxx::model::delete_many delete_op{filter_doc.view()};
bulk.append(delete_op);

일괄 작업을 실행 하려면 쓰기 (write) 모델이 포함된 mongocxx::bulk_write 클래스의 인스턴스 에서 execute() 메서드를 호출합니다. 기본값 execute() 메서드는 mongocxx::bulk_write 인스턴스 에 추가되는 순서대로 작업을 실행합니다.

The following example performs the insert, update, replace, and delete operations specified in the preceding sections of this guide by appending each corresponding write model to an instance of mongocxx::bulk_write and calling the execute() method. Then, it prints the number of modified documents:

auto bulk = collection.create_bulk_write();
// Specifies documents to insert, update, replace, or delete
auto insert_doc = make_document(kvp("name", "Mongo's Deli"),
kvp("cuisine", "Sandwiches"),
kvp("borough", "Manhattan"),
kvp("restaurant_id", "1234"));
auto update_filter = make_document(kvp("name", "Mongo's Deli"));
auto update_doc = make_document(kvp("$set", make_document(kvp("cuisine", "Sandwiches and Salads"))));
auto replace_filter = make_document(kvp("restaurant_id", "1234"));
auto replace_doc = make_document(kvp("name", "Mongo's Deli"),
kvp("cuisine", "Sandwiches and Salads"),
kvp("borough", "Brooklyn"),
kvp("restaurant_id", "5678"));
auto delete_filter = make_document(kvp("borough", "Manhattan"));
// Creates write models for each write operation using the preceding documents
mongocxx::model::insert_one insert_op{insert_doc.view()};
mongocxx::model::update_many update_op{update_filter.view(), update_doc.view()};
mongocxx::model::replace_one replace_op{replace_filter.view(), replace_doc.view()};
mongocxx::model::delete_many delete_op{delete_filter.view()};
// Appends each write model to the bulk operation
bulk.append(insert_op);
bulk.append(update_op);
bulk.append(replace_op);
bulk.append(delete_op);
// Runs the bulk operation
auto result = bulk.execute();
std::cout << "Modified documents: " << result->modified_count() << std::endl;
Modified documents: 2

쓰기 (write) 작업 중 하나라도 실패하면 C++ 운전자 는 mongocxx::bulk_write_exception 를 발생시키고 추가 작업을 수행하지 않습니다.

modified_count() 함수에 학습 보려면 이 가이드 의 반환 값 섹션을 참조하세요.

mongocxx::options::bulk_write 클래스의 인스턴스 를 매개변수로 전달하여 create_bulk_write() 메서드의 동작을 수정할 수 있습니다. 다음 표에서는 mongocxx::options::bulk_write 인스턴스 에서 설정하다 수 있는 필드에 대해 설명합니다.

필드
설명

ordered

true인 경우 드라이버는 제공된 순서대로 쓰기 (write) 작업을 수행합니다. 오류가 발생하면 나머지 작업은 수행되지 않습니다.

false인 경우 드라이버는 임의의 순서대로 작업을 수행하고 모든 작업을 수행하려고 시도합니다.
기본값은 true입니다.

bypass_document_validation

Specifies whether the operation bypasses document-level validation. For more information, see Schema Validation in the MongoDB Server manual.
Defaults to false.

write_concern

Specifies the write concern for the bulk operation. For more information, see Write Concern 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.

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.

The following example calls the create_bulk_write() method from the Create a Bulk Write Instance example on this page, but sets the ordered field of a mongocxx::options::bulk_write instance to false:

mongocxx::options::bulk_write opts;
opts.ordered(false);
auto bulk = collection.create_bulk_write(opts);

순서가 지정되지 않은 대량 쓰기 (write) 의 쓰기 (write) 작업 중 하나라도 실패하면 C++ 운전자 는 모든 작업을 시도한 후에만 오류를 보고합니다.

참고

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

execute() 메서드는 mongocxx::result::bulk_write 클래스의 인스턴스 를 반환합니다. mongocxx::result::bulk_write 클래스에는 다음 멤버 함수가 포함되어 있습니다.

기능
설명

deleted_count()

삭제된 문서 수를 반환합니다(있는 경우).

inserted_count()

삽입된 문서 수를 반환합니다(있는 경우).

matched_count()

해당하는 경우 업데이트 와 일치하는 문서 수를 반환합니다.

modified_count()

수정된 문서 수를 반환합니다(있는 경우).

upserted_count()

업서트된 문서 수(있는 경우)를 반환합니다.

upserted_ids()

해당하는 경우 업서트된 문서의 _id 에 대한 작업 인덱스 맵을 반환합니다.

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

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