문서 삽입
개요
이 가이드에서는 MongoDB 컬렉션에 문서를 삽입하는 방법을 배울 수 있습니다.
MongoDB에서 문서를 찾고, 업데이트하고, 삭제하려면 먼저 문서를 삽입해야 합니다. 다음 방법을 사용하여 문서를 삽입할 수 있습니다.
insert_one()
하나의 문서를 삽입하려면insert_many()
하나 이상의 문서를 삽입하려면
이 가이드에는 다음 섹션이 포함되어 있습니다.
_id 필드
MongoDB collection에서 각 문서에는 고유한 _id
필드 값이 포함 되어야 합니다. 드라이버는 collection에 데이터를 삽입할 때 각 문서에 대한 고유 값을 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).await?; println!("Inserted document with _id: {}", insert_one_result.inserted_id);
Inserted document with _id: 8
팁
존재하지 않는 데이터베이스 및 collection
쓰기 작업을 수행할 때 데이터베이스와 컬렉션이 존재하지 않는 경우 서버에서 자동으로 생성합니다.
insert_one 동작 수정
옵션 빌더 메서드를 insert_one()
에 연결하여 insert_one()
메서드의 동작을 수정할 수 있습니다. 이러한 옵션 빌더 메서드 설정하다 InsertOneOptions
구조체 필드를 설정합니다.
참고
설정 옵션
옵션 빌더 메서드를 insert_one()
메서드 호출에 직접 연결하여 InsertOneOptions
필드를 설정하다 수 있습니다. 이전 버전의 운전자 를 사용하는 경우 옵션 빌더 메서드를 builder()
메서드에 연결하여 InsertOneOptions
인스턴스 를 구성해야 합니다. 그런 다음 옵션 인스턴스 를 insert_one()
에 매개 변수로 전달합니다.
다음 표에서는 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: bool Default: 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: Bson Default: None |
다음 코드는 bypass_document_validation()
메서드를 insert_one()
메서드에 연결하여 bypass_document_validation
필드 를 설정하다 하는 방법을 보여줍니다.
let _result = my_coll.insert_one(doc) .bypass_document_validation(true) .await?;
여러 문서를 삽입합니다.
여러 문서를 컬렉션에 삽입하려면 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).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 동작 수정
옵션 빌더 메서드를 insert_many()
에 연결하여 insert_many()
메서드의 동작을 수정할 수 있습니다. 이러한 옵션 빌더 메서드 설정하다 InsertManyOptions
구조체 필드를 설정합니다.
다음 표에서는 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: bool Default: 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: bool Default: 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: Bson Default: None |
다음 코드는 comment()
메서드를 insert_many()
메서드에 연결하여 comment
필드 를 설정하다 하는 방법을 보여줍니다.
let _result = my_coll.insert_many(docs) .comment(Some("hello world".into())) .await?;
순서가 지정된 동작 예제
다음 문서를 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" }
이러한 문서를 삽입하려고 하는 경우 결과는 ordered()
옵션 빌더 메서드에 전달된 값에 따라 달라집니다.
true
값( 기본값 )을 전달하면 운전자 는 중복된_id
값이 있는 문서 를 삽입하려고 할 때BulkWriteError
를 발생시킵니다. 그러나 운전자 는 여전히 오류가 발생하기 전에 문서를 삽입합니다.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: 1, title: "Blueberries for Sal".to_string(), author: "".to_string() }, Book { _id: 3, title: "Goodnight Moon".to_string(), author: "".to_string() } ]; my_coll.insert_many(docs).ordered(false).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 문서를 참조하세요.