개요
이 가이드 에서는 대량 쓰기 (write) 작업 을 사용하여 단일 데이터베이스 호출에서 여러 쓰기 (write) 작업을 수행하는 방법에 학습 설명합니다.
컬렉션 에 문서 를 삽입하고 다른 여러 문서를 업데이트 한 다음 문서 를 삭제 하려는 시나리오를 가정해 보겠습니다. 개별 메서드를 사용하는 경우 각 작업에는 자체 데이터베이스 호출이 필요합니다. 대신 대량 작업을 사용하여 데이터베이스 에 대한 호출 수를 줄일 수 있습니다.
샘플 데이터
이 가이드 의 예제에서는 Atlas 샘플 데이터 세트 의 sample_restaurants 데이터베이스 에 있는 restaurants 컬렉션 을 사용합니다. C++ 애플리케이션 에서 이 컬렉션 에 액세스 하려면 Atlas cluster 에 연결하는 mongocxx::client 를 인스턴스화하고 db 및 collection 변수에 다음 값을 할당합니다.
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_onemongocxx::model::update_onemongocxx::model::update_manymongocxx::model::replace_onemongocxx::model::delete_onemongocxx::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 인스턴스 에 추가되는 순서대로 작업을 실행합니다.
다음 예시 에서는 각 해당 쓰기 (write) 모델을 mongocxx::bulk_write 인스턴스 에 추가하고 execute() 메서드를 호출하여 이 가이드 의 이전 섹션에 지정된 삽입, 업데이트, 바꾸기 및 삭제 작업을 수행합니다. 그런 다음 수정된 문서 수를 출력합니다.
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 인스턴스 에서 설정하다 수 있는 필드에 대해 설명합니다.
필드 | 설명 |
|---|---|
| 인 |
| 작업이 문서 수준 유효성 검사 우회할지 여부를 지정합니다. 자세한 내용은 MongoDB Server 매뉴얼의 스키마 유효성 검사 참조하세요. |
| 대량 작업에 대한 쓰기 고려 (write concern) 지정합니다. 자세한 내용은 MongoDB Server 매뉴얼의 쓰기 고려를 참조하세요. |
| 작업에 주석을 첨부합니다. 자세한 내용은 MongoDB Server 매뉴얼의 삭제 명령 필드 가이드 참조하세요. |
| 작업 가독성을 높이기 위해 값 목록이 포함된 문서 지정합니다. 값은 문서 필드를 참조하지 않는 상수 또는 닫힌 표현식이어야 합니다. 자세한 내용은 MongoDB Server 매뉴얼의 let 성명서 참조하세요. |
다음 예시 에서는 이 페이지 의 대량 쓰기 인스턴스 만들기 예시 에서 create_bulk_write() 메서드를 호출하지만 mongocxx::options::bulk_write 인스턴스 의 ordered 필드 를 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 클래스에는 다음 멤버 함수가 포함되어 있습니다.
기능 | 설명 |
|---|---|
| 삭제된 문서 수를 반환합니다(있는 경우). |
| 삽입된 문서 수를 반환합니다(있는 경우). |
| 해당하는 경우 업데이트 와 일치하는 문서 수를 반환합니다. |
| 수정된 문서 수를 반환합니다(있는 경우). |
| 업서트된 문서 수(있는 경우)를 반환합니다. |
| 해당하는 경우 업서트된 문서의 |
추가 정보
개별 쓰기 작업을 수행하는 방법을 알아보려면 다음 가이드를 참조하세요.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.