개요
이 가이드 에서는 C++ 운전자 를 사용하여 삽입 작업 을 수행하여 MongoDB 컬렉션 에 문서를 추가하는 방법을 학습 수 있습니다.
삽입 작업은 하나 이상의 문서를 MongoDB 컬렉션 에 삽입합니다. insert_one() 메서드를 사용하여 단일 문서 를 삽입하거나 insert_many() 메서드를 사용하여 하나 이상의 문서를 삽입하여 삽입 작업을 수행할 수 있습니다.
샘플 데이터
The examples in this guide use the sample_restaurants.restaurants collection from the Atlas sample datasets. To access this collection from your C++ application, instantiate a 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 시작하기 가이드 를 참조하세요.
_id 필드
MongoDB 컬렉션에서 각 문서에는 고유한 필드 값이 있는 _id 필드가 포함되어야 합니다.
MongoDB를 사용하면 이 필드를 두 가지 방법으로 관리할 수 있습니다.
각
_id필드 값이 고유하도록 각 문서에 대해 이 필드를 직접 설정할 수 있습니다.드라이버가 각 문서
_id에 대해 고유한ObjectId값을 자동으로 생성하도록 할 수 있습니다.
고유성을 보장할 수 없는 경우 드라이버가 _id 값을 자동으로 생성하도록 하는 것이 좋습니다.
참고
중복된 _id 값은 고유 인덱스 제약 조건을 위반하여 운전자 가 mongocxx::bulk_write_exception 오류를 반환하도록 합니다.
_id 필드에 대해 자세히 알아보려면 MongoDB Server 매뉴얼의 고유 인덱스 가이드를 참조하세요.
문서 구조 및 규칙에 대해 자세히 알아보려면 MongoDB Server 매뉴얼의 문서 가이드를 참조하세요.
문서 하나 삽입
MongoDB 컬렉션에 단일 문서를 추가하려면 insert_one() 메서드를 호출하고 추가하려는 문서를 전달합니다.
다음 예시에서는 restaurants 컬렉션에 문서를 삽입합니다.
auto result = collection.insert_one(make_document(kvp("name", "Mongo's Burgers")));
여러 문서를 삽입합니다.
MongoDB 컬렉션 에 여러 문서를 추가하려면 insert_many() 메서드를 호출하고 추가하려는 문서를 저장하는 벡터를 전달합니다.
다음 예시 에서는 restaurants 컬렉션 에 두 개의 문서를 삽입합니다.
std::vector<bsoncxx::document::value> restaurants; restaurants.push_back(make_document(kvp("name", "Mongo's Burgers"))); restaurants.push_back(make_document(kvp("name", "Mongo's Pizza"))); auto result = collection.insert_many(restaurants);
삽입 동작 수정
mongocxx::options::insert 클래스의 인스턴스 를 선택적 매개변수로 전달하여 insert_one() 및 insert_many() 메서드의 동작을 수정할 수 있습니다. 다음 표에서는 mongocxx::options::insert 인스턴스 에서 설정하다 수 있는 필드에 대해 설명합니다.
필드 | 설명 |
|---|---|
| If set to |
| 작업에 대한 쓰기 고려(write concern)를 설정합니다. |
|
|
| A comment to attach to the operation. For more information, see the insert command fields guide in the MongoDB Server manual. |
예시
다음 코드에서는 insert_many() 메서드를 사용하여 컬렉션 에 세 개의 새 문서를 삽입합니다. mongocxx::options::insert 인스턴스 에서 bypass_document_validation 필드 가 true 로 설정하다 되어 있으므로 이 삽입 작업은 문서 수준 유효성 검사 를 우회합니다.
std::vector<bsoncxx::document::value> docs; docs.push_back(make_document(kvp("name", "Mongo's Burgers"))); docs.push_back(make_document(kvp("name", "Mongo's Pizza"))); docs.push_back(make_document(kvp("name", "Mongo's Tacos"))); mongocxx::options::insert opts; opts.bypass_document_validation(true); auto result = collection.insert_many(docs, opts);
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.