Collection 인스턴스 에서 insert_one() 메서드를 호출하여 컬렉션 에 문서 삽입할 수 있습니다.
Collection 인스턴스 를 매개변수화한 것과 동일한 유형의 문서 를 삽입해야 합니다. 예를 예시 MyStruct 구조체를 사용하여 컬렉션 을 매개 변수화한 경우 MyStruct 인스턴스 를 insert_one() 메서드에 매개 변수로 전달하여 문서 를 삽입합니다. 유형 매개변수 지정에 학습 보려면 데이터베이스 및 컬렉션 가이드 의 컬렉션 매개변수화 섹션을 참조하세요.
insert_one() 메서드는 새로 삽입된 문서 의 _id 필드 포함된 InsertOneResult 유형을 반환합니다.
insert_one() 메서드에 대해 자세히 알아보려면 문서 삽입 가이드를 참조하세요.
예시
이 예시 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("...")