개요
이 가이드에서는 MongoDB 컬렉션에 문서를 삽입하는 방법을 배울 수 있습니다.
MongoDB에서 문서를 찾고, 업데이트하고, 삭제하려면 먼저 문서를 삽입해야 합니다. 다음 방법을 사용하여 문서를 삽입할 수 있습니다.
insert_one()하나의 문서를 삽입하려면insert_many()하나 이상의 문서를 삽입하려면
이 가이드에는 다음 섹션이 포함되어 있습니다.
_id 필드
MongoDB에서 각 문서에는 고유한 _id 필드가 포함 되어야 합니다. MongoDB를 사용하면 다음과 같은 방법으로 이 필드를 관리할 수 있습니다.
이 필드를 직접 관리하여 설정한 각
_id값이 고유한지 확인합니다.드라이버가 고유한
ObjectId값을 자동으로 생성하도록 합니다. 삽입을 수행할 때_id필드에 값을 지정하지 않으면 드라이버는 각 문서에 대해 고유한ObjectId값을 생성합니다.
고유성에 대한 강력한 보장을 제공하지 않는 한 드라이버가 문서에 대해 _id 값을 자동으로 생성하도록 하는 것이 좋습니다.
중요
중복 _id 값
중복된 _id 값이 포함된 쓰기 작업을 수행하려고 하면 중복된 값이 고유 인덱스 제약 조건을 위반하여 쓰기 작업이 실패하게 됩니다.
_id 필드에 대해 자세히 알아보려면 MongoDB Server 매뉴얼의 고유 인덱스 를 참조하세요.
문서 구조 및 규칙에 대해 자세히 알아보려면 MongoDB Server 매뉴얼의 문서 를 참조하세요.
문서 삽입
단일 문서를 컬렉션에 삽입하려면 insert_one() 메서드를 사용합니다.
성공적으로 삽입되면 메서드는 삽입된 문서의 _id 를 포함하는 InsertOneResult 인스턴스를 반환합니다.
예시
다음 예제에서는 insert_one() 메서드를 사용하여 books collection에 문서를 삽입합니다.
let my_coll: Collection<Book> = client.database("db").collection("books"); let doc = Book { _id: 8, title: "Atonement".to_string(), author: "Ian McEwan".to_string() }; let insert_one_result = my_coll.insert_one(doc, None).await?; println!("Inserted document with _id: {}", insert_one_result.inserted_id);
Inserted document with _id: 8
팁
존재하지 않는 데이터베이스 및 collection
쓰기 작업을 수행할 때 데이터베이스와 컬렉션이 존재하지 않는 경우 서버에서 자동으로 생성합니다.
insert_one 동작 수정
InsertOneOptions 구조체를 구성하고 전달하여 insert_one() 메서드의 동작을 수정할 수 있습니다.
참고
인스턴스화 옵션
Rust 드라이버는 InsertOneOptions 을(를) 포함하여 다양한 유형을 생성하기 위해 빌더(Builder) 디자인 패턴을 구현합니다. 각 유형의 builder() 메서드를 사용하여 옵션 빌더 함수를 한 번에 하나씩 연결하여 옵션 인스턴스를 구성할 수 있습니다.
다음 표에서는 InsertOneOptions 에서 사용할 수 있는 옵션에 대해 설명합니다.
옵션 | 설명 |
|---|---|
| If true, allows the driver to perform a write that violates
document-level validation. To learn more about validation, see
the guide on Schema Validation.Type: boolDefault: false |
| The write concern for the operation. If you don't set this
option, the operation inherits the write concern set for
the collection. To learn more about write concerns, see
Write Concern in the
Server manual. Type: WriteConcern |
| An arbitrary Bson value tied to the operation to trace
it through the database profiler, currentOp, and
logs. This option is available only when connecting to
MongoDB Server versions 4.4 and later.Type: BsonDefault: None |
다음 코드는 InsertOneOptions 인스턴스를 구성하는 방법을 보여줍니다.
let _opts = InsertOneOptions::builder() .bypass_document_validation(true) .build();
여러 문서를 삽입합니다.
여러 문서를 컬렉션에 삽입하려면 insert_many() 메서드를 사용합니다.
성공적으로 삽입되면 메서드는 InsertManyResult _id 삽입된 문서의 값이 포함된 인스턴스를 반환합니다.
예시
다음 예제에서는 insert_many() 메서드를 사용하여 books collection에 여러 문서를 삽입합니다.
let docs = vec![ Book { _id: 5, title: "Cat's Cradle".to_string(), author: "Kurt Vonnegut Jr.".to_string() }, Book { _id: 6, title: "In Memory of Memory".to_string(), author: "Maria Stepanova".to_string() }, Book { _id: 7, title: "Pride and Prejudice".to_string(), author: "Jane Austen".to_string() } ]; let insert_many_result = my_coll.insert_many(docs, None).await?; println!("Inserted documents with _ids:"); for (_key, value) in &insert_many_result.inserted_ids { println!("{:?}", value); }
Inserted documents with _ids: Int32(5) Int32(6) Int32(7)
팁
존재하지 않는 데이터베이스 및 collection
쓰기 작업을 수행할 때 데이터베이스와 컬렉션이 존재하지 않는 경우 서버에서 자동으로 생성합니다.
insert_many 동작 수정
InsertManyOptions 구조체를 구성하고 전달하여 insert_many() 메서드의 동작을 수정할 수 있습니다. 다음 표에서는 InsertManyOptions 에서 사용할 수 있는 옵션에 대해 설명합니다.
옵션 | 설명 |
|---|---|
| If true, allows the driver to perform a write that violates
document-level validation. To learn more about validation, see
the guide on Schema Validation.Type: boolDefault: false |
| If true, when any insert fails, the operation returns
without inserting the remaining documents. If false, even
if an insert fails, the operation continues with the remaining
writes. To learn more about ordered inserts, see the
Ordered Behavior Example section
of this guide.Type: boolDefault: true |
| The write concern for the operation. If you don't set this
option, the operation inherits the write concern set for
the collection. To learn more about write concerns, see
Write Concern in the
Server manual. Type: WriteConcern |
| An arbitrary Bson value tied to the operation to trace
it through the database profiler, currentOp, and
logs. This option is available only when connecting to
MongoDB Server versions 4.4 and later.Type: BsonDefault: None |
다음 코드는 InsertManyOptions 인스턴스를 구성하는 방법을 보여줍니다.
let _opts = InsertManyOptions::builder() .comment(Some("hello world".into())) .build();
순서가 지정된 동작 예제
다음 문서를 books collection에 삽입한다고 가정합니다.
{ "_id": 1, "title": "Where the Wild Things Are" } { "_id": 2, "title": "The Very Hungry Caterpillar" } { "_id": 1, "title": "Blueberries for Sal" } { "_id": 3, "title": "Goodnight Moon" }
이러한 문서를 삽입하려고 할 때 결과는 InsertManyOptions 의 ordered 옵션 값에 따라 달라집니다.
ordered가true(기본값)인 경우 드라이버는 중복된_id값이 있는 문서를 삽입하려고 시도할 때BulkWriteError를 발생시킵니다. 그러나 오류가 발생하기 전에 드라이버는 여전히 문서를 삽입합니다.ordered를false로 설정한 경우 드라이버는 중복된_id값이 있는 문서를 삽입하려고 할 때 여전히BulkWriteError를 발생시키지만 그 외의 모든 문서는 삽입합니다.
다음 코드는 순서가 지정되지 않은 쓰기 작업을 수행하여 앞에 설명한 문서를 삽입하는 방법을 보여줍니다.
let docs = vec![ Book { _id: 1, title: "Where the Wild Things Are".to_string(), author: "".to_string() }, Book { _id: 2, title: "The Very Hungry Caterpillar".to_string(), author: "".to_string() }, Book { _id: 4, title: "Blueberries for Sal".to_string(), author: "".to_string() }, Book { _id: 3, title: "Goodnight Moon".to_string(), author: "".to_string() } ]; let opts = InsertManyOptions::builder().ordered(false).build(); my_coll.insert_many(docs, opts).await?;
이 작업으로 인해 BulkWriteError 이(가) 발생하더라도 collection에서 오류가 발생하지 않는 문서를 찾을 수 있습니다.
{ "_id": 1, "title": "Where the Wild Things Are" } { "_id": 2, "title": "The Very Hungry Caterpillar" } { "_id": 3, "title": "Goodnight Moon" }
추가 정보
삽입 작업의 실행 가능한 예시는 다음 사용 예시를 참조하세요:
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.