Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Rust 드라이버
/

여러 문서를 삽입합니다.

인스턴스 에서insert_many() 메서드를 호출하여 컬렉션 에 여러 문서를 삽입할 수 있습니다.Collection

하나 이상의 문서가 포함된 벡터를 insert_many() 메서드에 전달하여 컬렉션에 삽입합니다. 이러한 문서는 Collection 인스턴스를 매개변수화한 유형의 인스턴스여야 합니다. 예를 들어 MyStruct 구조체를 사용하여 컬렉션을 매개변수화한 경우 MyStruct 인스턴스로 구성된 벡터를 insert_many() 메서드에 매개변수로 전달합니다.

단일 문서 삽입하려면 insert_one() 메서드를 대신 사용하는 것이 좋습니다. 이 메서드를 사용하는 실행 가능한 코드 예시 는 문서 삽입 사용 예시 참조하세요.

메서드는 삽입된 문서의 값을 참조하는 insert_many() InsertManyResult 유형을 반환합니다._id

collection에 문서를 삽입하는 방법에 대해 자세히 알아보려면 문서 삽입 가이드를 참조하세요.

이 예에서는 sample_restaurants 데이터베이스의 restaurants collection에 문서를 삽입합니다. 이 예제에서는 namecuisine 필드가 포함된 Restaurant 구조체를 사용하여 컬렉션에 삽입되는 문서를 모델링합니다.

이 예에서는 문서 벡터를 insert_many() 메서드에 매개변수로 전달합니다.

Asynchronous 또는 Synchronous 탭을 선택하여 각 런타임에 해당하는 코드를 확인합니다.

use mongodb::{
bson::doc,
Client,
Collection
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: String,
}
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
let my_coll: Collection<Restaurant> = client
.database("sample_restaurants")
.collection("restaurants");
let docs = vec! [
Restaurant {
name: "While in Kathmandu".to_string(),
cuisine: "Nepalese".to_string(),
},
Restaurant {
name: "Cafe Himalaya".to_string(),
cuisine: "Nepalese".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);
}
Ok(())
}
Inserted documents with _ids:
ObjectId("...")
ObjectId("...")
use mongodb::{
bson::doc,
sync::{Client, Collection}
};
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
cuisine: String,
}
fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri)?;
let my_coll: Collection<Restaurant> = client
.database("sample_restaurants")
.collection("restaurants");
let docs = vec! [
Restaurant {
name: "While in Kathmandu".to_string(),
cuisine: "Nepalese".to_string(),
},
Restaurant {
name: "Cafe Himalaya".to_string(),
cuisine: "Nepalese".to_string(),
}
];
let insert_many_result = my_coll.insert_many(docs, None)?;
println!("Inserted documents with _ids:");
for (_key, value) in &insert_many_result.inserted_ids {
println!("{}", value);
}
Ok(())
}
Inserted documents with _ids:
ObjectId("...")
ObjectId("...")

돌아가기

insertOne