개요
이 가이드 에서는 C++ 운전자 를 사용하여 MongoDB 컬렉션 에서 바꾸기 작업을 실행 하는 방법을 학습 수 있습니다. 바꾸기 작업은 대상 문서 에서 _id 필드 를 제외한 모든 필드를 제거하고 새 필드로 바꿉니다. replace_one() 메서드를 호출하여 단일 문서 를 바꿀 수 있습니다.
샘플 데이터
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 시작하기 가이드 를 참조하세요.
대체 작업
replace_one() 메서드를 호출하여 바꾸기 작업을 수행할 수 있습니다. 이 메서드는 검색 기준과 일치하는 첫 번째 문서 에서 _id 필드 를 제외한 모든 필드를 제거합니다. 그런 다음 지정한 필드와 값이 문서 에 삽입됩니다.
이 replace_one() 메서드에는 다음 매개 변수가 필요합니다.
쿼리 필터하다 문서: 대체할 문서 를 지정합니다. 쿼리 필터에 대한 자세한 내용은 MongoDB Server 매뉴얼의 필터 문서 쿼리를 참조하세요.
문서 바꾸기: 새 문서 에 삽입할 필드와 값을 지정합니다.
중요
_id 필드의 값은 변경할 수 없습니다. 대체 문서에서 _id 필드 값을 지정하는 경우 기존 문서의 _id 값과 일치해야 합니다.
하나의 문서 교체 예시
다음 예시 에서는 replace_one() 메서드를 사용하여 name 필드 값이 "Nobu" 인 문서 를 name 필드 값이 "La Bernadin"인 새 문서 로 바꿉니다.
auto query_filter = make_document(kvp("name", "Nobu")); auto replace_doc = make_document(kvp("name", "La Bernadin")); auto result = collection.replace_one(query_filter.view(), replace_doc.view());
문서 를 성공적으로 교체했는지 확인하려면 find_one() 메서드를 사용하여 새 문서 를 인쇄할 수 있습니다.
auto new_doc = collection.find_one(make_document(kvp("name", "La Bernadin"))); std::cout << "New document: " << bsoncxx::to_json(*new_doc) << std::endl;
find_one() 메서드에 대해 자세히 알아보려면 데이터 조회 가이드에서 하나의 문서 찾기 를 참조하세요.
옵션
mongocxx::options::replace 클래스의 인스턴스 를 선택적 인수로 전달하여 replace_one() 메서드의 동작을 수정할 수 있습니다. 다음 표에서는 mongocxx::options::replace 인스턴스 에서 설정하다 수 있는 필드에 대해 설명합니다.
필드 | 설명 |
|---|---|
| Specifies whether the replace operation bypasses document validation. When set to |
| Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual. |
| 작업에 첨부할 유효한 BSON types의 주석을 지정합니다. 설정하다 되면 이 주석은 다음 위치에서 이 명령의 레코드와 함께 표시됩니다.
For more information, see the insert Command Fields guide in the MongoDB Server manual. |
| Specifies the index to scan for documents that match the query filter. For more information, see the hint field in the MongoDB Server manual. |
| Specifies a document containing variables and their values to be used in the |
| 쿼리 필터와 일치하는 문서가 없는 경우 대체 작업에서 업서트 작업을 수행할지 여부를 지정합니다. |
| Sets the write concern for the operation. For more information, see Write Concern in the MongoDB Server manual. |
예시: 힌트 옵션
다음 예시 에서는 create_index() 메서드를 사용하여 name 필드 에 오름차순 단일 필드 인덱스 를 생성합니다. 그런 다음 hint 필드 를 새 인덱스 로 설정한 후 mongocxx::options::replace 객체 를 replace_one() 메서드에 전달합니다. 이는 name 필드 값이 "Nobu" 인 문서 를 대체할 때 name 필드 인덱스 를 검색 하도록 대체 작업에 지시합니다.
auto index_specification = make_document(kvp("name", 1)); collection.create_index(index_specification.view()); mongocxx::options::replace opts{}; opts.hint(mongocxx::hint{"name_1"}); auto query_filter = make_document(kvp("name", "Nobu")); auto replace_doc = make_document(kvp("name", "La Bernadin")); auto result = collection.replace_one(query_filter.view(), replace_doc.view(), opts);
인덱스에 학습 보려면 인덱스를 사용한 쿼리 최적화 가이드 를 참조하세요.
예시: 업서트 옵션
다음 예시 에서는 upsert 필드 값을 true 로 설정한 후 mongocxx::options::replace 객체 를 replace_one() 메서드에 전달합니다. 쿼리 필터하다 와 일치하는 문서가 없기 때문에 name 필드 값이 "Shake Shack" 인 새 문서 를 컬렉션 에 삽입하도록 바꾸기 작업을 지시합니다.
std::cout << "Total document count before replace_one(): " << collection.count_documents({}) << std::endl; mongocxx::options::replace opts{}; opts.upsert(true); auto query_filter = make_document(kvp("name", "In-N-Out Burger")); auto replace_doc = make_document(kvp("name", "Shake Shack")); auto result = collection.replace_one(query_filter.view(), replace_doc.view(), opts); std::cout << "Total document count after replace_one(): " << collection.count_documents({}) << std::endl;
반환 값
replace_one() 메서드는 mongocxx::result::replace 클래스의 인스턴스 를 반환합니다. 이 클래스에는 다음과 같은 멤버 함수가 포함되어 있습니다.
기능 | 설명 |
|---|---|
| 대체된 문서 수에 관계없이 쿼리 필터하다 와 일치하는 문서 수를 반환합니다. |
| 대체 작업으로 수정된 문서 수를 반환합니다. 교체된 문서 원본과 동일한 경우 해당 문서는 이 계산에 포함되지 않습니다. |
| 작업에 대한 대량 쓰기 (write) 결과를 반환합니다. |
| 운전자 업서트 수행한 경우 데이터베이스 에 업서트된 문서 의 ID 반환합니다. |
예시: match_count()
다음 예시 에서는 replace_one() 메서드를 사용하여 name 필드 값이 "Shake Shack" 인 문서 를 name 필드 값이 "In-N-Out Burger"인 새 문서 로 바꿉니다. 그런 다음 matched_count() 멤버 함수를 호출하여 쿼리 필터하다 와 일치하는 문서 수를 출력합니다.
auto query_filter = make_document(kvp("name", "Shake Shack")); auto replace_doc = make_document(kvp("name", "In-N-Out Burger")); auto result = collection.replace_one(query_filter.view(), replace_doc.view()); std::cout << "Matched documents: " << result->matched_count() << std::endl;
예제: upserted_id()
다음 예시 에서는 replace_one() 메서드를 사용하여 name 필드 값이 "In-N-Out Burger"인 문서 를 바꿉니다. upsert 옵션이 true 로 설정하다 되어 있기 때문에 C++ 운전자 는 쿼리 필터하다 가 기존 문서와 일치하지 않을 때 새 문서 를 삽입합니다. 그런 다음 이 코드는 upserted_id() 멤버 함수를 호출하여 업서트 문서 의 _id 필드 값을 출력합니다.
mongocxx::options::replace opts{}; opts.upsert(true); auto query_filter = make_document(kvp("name", "In-N-Out Burger")); auto replace_doc = make_document(kvp("name", "Shake Shack")); auto result = collection.replace_one(query_filter.view(), replace_doc.view(), opts); auto id = result->upserted_id()->get_value(); std::cout << "Upserted ID: " << id.get_oid().value.to_string() << std::endl;
추가 정보
쿼리 필터 생성에 대해 자세히 알아보려면 쿼리 지정 가이드를 참조하세요.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.