개요
이 가이드에서는 MongoDB 컬렉션에 문서를 삽입하는 방법을 배울 수 있습니다.
MongoDB에서 문서를 찾고, 업데이트하고, 삭제하려면 먼저 문서를 삽입해야 합니다. 다음 방법을 사용하여 문서를 삽입할 수 있습니다.
insert_one()하나의 문서를 삽입하려면insert_many()하나 이상의 문서를 삽입하려면
이 가이드에는 다음 섹션이 포함되어 있습니다.
_id 필드
MongoDB collection에서 각 문서에는 고유한 _id 필드 값이 포함 되어야 합니다. 드라이버는 collection에 데이터를 삽입할 때 각 문서에 대한 고유 값을 ObjectId 유형으로 자동으로 생성합니다.
사용자 지정 값을 설정하려는 경우 삽입 작업에 전달된 문서의 _id 필드에 값을 할당할 수 있습니다.
중요
중복 _id 값
중복된 _id 값을 포함하는 문서를 삽입하려고 하면 이러한 값은 고유 인덱스 제약 조건을 위반하여 쓰기 작업이 실패하게 됩니다.
_id 필드에 대해 자세히 알아보려면 MongoDB Server 매뉴얼의 고유 인덱스 를 참조하세요.
문서 구조 및 규칙에 대해 자세히 알아보려면 MongoDB Server 매뉴얼의 문서 를 참조하세요.
문서 삽입
단일 문서를 컬렉션에 삽입하려면 insert_one() 메서드를 사용합니다.
Collection 인스턴스를 매개변수화한 것과 동일한 유형의 문서를 삽입해야 합니다. 예를 들어, MyStruct 구조체로 collection을 매개변수화한 경우, MyStruct 인스턴스를 insert_one() 메서드에 매개변수로 전달하여 문서를 삽입합니다. 유형 매개변수 지정에 대해 자세히 알아보려면 데이터베이스 및 collection 가이드의 collection 매개변수화 섹션을 참조하세요.
삽입에 성공적인 하면 메서드는 새로 삽입된 문서 의 _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 에서 사용할 수 있는 옵션에 대해 설명합니다.
옵션 | 설명 |
|---|---|
|
|
| 작업에 대한 쓰기 고려 (write concern) . 이 옵션을 설정하다 하지 않으면 작업은 컬렉션 에 대해 설정하다 쓰기 고려 (write concern) 상속합니다. 쓰기 (write) 고려에 대해 자세히 학습 서버 매뉴얼에서 쓰기 고려를 참조하세요. |
|
|
다음 코드는 bypass_document_validation() 메서드를 insert_one() 메서드에 연결하여 bypass_document_validation 필드 를 설정하다 하는 방법을 보여줍니다.
let _result = my_coll.insert_one(doc) .bypass_document_validation(true) .await?;
전체 파일 예시: 문서 한 개 삽입
이 예시 sample_restaurants 데이터베이스 의 restaurants 컬렉션 에 문서 삽입합니다. insert_one() 메서드는 name, borough 및 cuisine 필드 값이 있는 문서 삽입합니다.
이 문서 Document 유형 또는 사용자 지정 데이터 유형 의 인스턴스 로 삽입할 수 있습니다. 컬렉션의 데이터를 나타내는 데이터 유형 지정하려면 강조 표시된 줄에서 다음 작업을 수행합니다.
컬렉션 문서에 액세스 하고 BSON 문서로 삽입하려면
<T>유형 매개변수를<Document>로 바꾸고<struct or doc>자리 표시자를insert_doc로 바꿉니다.컬렉션 문서를
Restaurant구조체의 인스턴스로 액세스 하고 삽입하려면<T>유형 매개변수를<Restaurant>로 바꾸고<struct or doc>자리 표시자를insert_struct로 바꿉니다.Restaurant구조체는 코드 파일 상단에 정의되어 있습니다.
Asynchronous 또는 Synchronous 탭을 선택하여 각 런타임에 해당하는 코드를 확인합니다.
use std::env; use mongodb::{ bson::{doc, Document}, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant { borough: String, cuisine: String, name: String, } async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let insert_doc = doc! { "name": "Sea Stone Tavern", "cuisine": "Greek", "borough": "Queens", }; let insert_struct = Restaurant { name: "Sea Stone Tavern".to_string(), cuisine: "Greek".to_string(), borough: "Queens".to_string(), }; // Replace <struct or doc> with the insert_struct or insert_doc variable let res = my_coll.insert_one(<struct or doc>).await?; println!("Inserted a document with _id: {}", res.inserted_id); Ok(()) }
Inserted a document with _id: ObjectId("...")
use std::env; use mongodb::{ bson::{doc, Document}, sync::{ Client, Collection } }; use serde::{ Deserialize, Serialize }; struct Restaurant { borough: String, cuisine: String, name: String, } fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let insert_doc = doc! { "name": "Sea Stone Tavern", "cuisine": "Greek", "borough": "Queens", }; let insert_struct = Restaurant { name: "Sea Stone Tavern".to_string(), cuisine: "Greek".to_string(), borough: "Queens".to_string(), }; // Replace <struct or doc> with the insert_struct or insert_doc variable let res = my_coll.insert_one(<struct or doc>).run()?; println!("Inserted a document with _id: {}", res.inserted_id); Ok(()) }
Inserted a document with _id: ObjectId("...")
여러 문서를 삽입합니다.
여러 문서를 컬렉션에 삽입하려면 insert_many() 메서드를 사용합니다.
하나 이상의 문서가 포함된 벡터를 insert_many() 메서드에 전달하여 컬렉션에 삽입합니다. 이러한 문서는 Collection 인스턴스를 매개변수화한 유형의 인스턴스여야 합니다. 예를 들어 MyStruct 구조체를 사용하여 컬렉션을 매개변수화한 경우 MyStruct 인스턴스로 구성된 벡터를 insert_many() 메서드에 매개변수로 전달합니다.
삽입에 성공적인 하면 메서드는 삽입된 문서의 _id 값을 참조하는 InsertManyResult 유형을 반환합니다.
예시
다음 예제에서는 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 에서 사용할 수 있는 옵션에 대해 설명합니다.
옵션 | 설명 |
|---|---|
|
|
|
|
| 작업에 대한 쓰기 고려 (write concern) . 이 옵션을 설정하다 하지 않으면 작업은 컬렉션 에 대해 설정하다 쓰기 고려 (write concern) 상속합니다. 쓰기 (write) 고려에 대해 자세히 학습 서버 매뉴얼에서 쓰기 고려를 참조하세요. |
|
|
다음 코드는 comment() 메서드를 insert_many() 메서드에 연결하여 comment 필드 를 설정하다 하는 방법을 보여줍니다.
let _result = my_coll.insert_many(docs) .comment(Some("hello world".into())) .await?;
전체 파일 예시: 여러 문서 삽입
이 예시 sample_restaurants 데이터베이스 의 restaurants 컬렉션 에 여러 문서를 삽입합니다. 이 예시 insert_many() 메서드에 문서 벡터를 전달하여 name 및 cuisine 필드 값이 있는 문서를 삽입합니다.
이러한 문서를 Document 유형 또는 사용자 지정 데이터 유형 의 인스턴스로 삽입할 수 있습니다. 컬렉션의 데이터를 나타내는 데이터 유형 지정하려면 강조 표시된 줄에서 다음 작업을 수행합니다.
컬렉션 문서에 액세스 하고 BSON 문서로 삽입하려면
<T>유형 매개변수를<Document>로 바꾸고<struct or doc>자리 표시자를insert_docs로 바꿉니다.컬렉션 문서를
Restaurant구조체의 인스턴스로 액세스 하고 삽입하려면<T>유형 매개변수를<Restaurant>로 바꾸고<struct or doc>자리 표시자를insert_structs로 바꿉니다.Restaurant구조체는 코드 파일 상단에 정의되어 있습니다.
Asynchronous 또는 Synchronous 탭을 선택하여 각 런타임에 해당하는 코드를 확인합니다.
use mongodb::{ bson::{doc, Document}, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: String, } async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let insert_docs = vec! [ doc! { "name": "While in Kathmandu", "cuisine": "Nepalese", }, doc! { "name": "Cafe Himalaya", "cuisine": "Nepalese", } ]; let insert_structs = vec! [ Restaurant { name: "While in Kathmandu".to_string(), cuisine: "Nepalese".to_string(), }, Restaurant { name: "Cafe Himalaya".to_string(), cuisine: "Nepalese".to_string(), } ]; // Replace <structs or docs> with the insert_structs or insert_docs variable let insert_many_result = my_coll.insert_many(<structs or docs>).await?; println!("Inserted documents with _ids:"); for (_key, value) in &insert_many_result.inserted_ids { println!("{}", value); } Ok(()) }
Inserted documents with _ids: ObjectId("...") ObjectId("...")
use mongodb::{ bson::{doc, Document}, sync::{Client, Collection} }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: String, } fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let insert_docs = vec! [ doc! { "name": "While in Kathmandu", "cuisine": "Nepalese", }, doc! { "name": "Cafe Himalaya", "cuisine": "Nepalese", } ]; let insert_structs = vec! [ Restaurant { name: "While in Kathmandu".to_string(), cuisine: "Nepalese".to_string(), }, Restaurant { name: "Cafe Himalaya".to_string(), cuisine: "Nepalese".to_string(), } ]; // Replace <structs or docs> with the insert_structs or insert_docs variable let insert_many_result = my_coll.insert_many(<structs or docs>).run()?; println!("Inserted documents with _ids:"); for (_key, value) in &insert_many_result.inserted_ids { println!("{}", value); } Ok(()) }
Inserted documents with _ids: ObjectId("...") ObjectId("...")
순서가 지정된 동작 예제
다음 문서를 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 문서를 참조하세요.