Collection 인스턴스 에서 insert_many() 메서드를 호출하여 컬렉션 에 여러 문서를 삽입할 수 있습니다.
하나 이상의 문서가 포함된 벡터를 insert_many() 메서드에 전달하여 컬렉션에 삽입합니다. 이러한 문서는 Collection 인스턴스를 매개변수화한 유형의 인스턴스여야 합니다. 예를 들어 MyStruct 구조체를 사용하여 컬렉션을 매개변수화한 경우 MyStruct 인스턴스로 구성된 벡터를 insert_many() 메서드에 매개변수로 전달합니다.
팁
단일 문서 삽입하려면 insert_one() 메서드를 대신 사용하는 것이 좋습니다. 이 메서드를 사용하는 실행 가능한 코드 예시는 문서 삽입 사용 예시 참조하세요.
insert_many() 메서드는 삽입된 문서의 _id 값을 참조하는 InsertManyResult 유형을 반환합니다.
collection에 문서를 삽입하는 방법에 대해 자세히 알아보려면 문서 삽입 가이드를 참조하세요.
예시
이 예시 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("...")