Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Menu Docs
Página inicial do Docs
/ / /
Driver Rust
/

Insira vários documentos

Você pode inserir vários documentos em uma coleção chamando o métodoinsert_many() em uma Collection instância.

Passe um vetor contendo um ou mais documento para o método insert_many() para inseri-los na sua collection. Esses documentos devem ser instâncias do tipo com o qual você parametrizou sua instância Collection . Por exemplo, se você parametrizou sua collection com a estrutura MyStruct , passe um vetor de instâncias MyStruct como parâmetro para o método insert_many() .

Dica

Para inserir um único documento, considere usar o insert_one() no lugar. Para obter um exemplo de código executável que usa esse método, consulte o exemplo de uso Inserir um documento .

O insert_many() método retorna um InsertManyResult tipo que referencia os _id valores dos documentos inseridos.

Para saber mais sobre como inserir documento em uma collection, consulte o guia Inserir documento .

Este exemplo insere documento na collection restaurants do reconhecimento de data center sample_restaurants . O exemplo utiliza uma estrutura Restaurant contendo os campos name e cuisine para modelar os documentos que estão sendo inseridos na collection.

Este exemplo passa um vetor de documentos como parâmetro para o método insert_many() .

Selecione a aba Asynchronous ou Synchronous para ver o código correspondente para cada tempo de execução:

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).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).run()?;
println!("Inserted documents with _ids:");
for (_key, value) in &insert_many_result.inserted_ids {
println!("{}", value);
}
Ok(())
}
Inserted documents with _ids:
ObjectId("...")
ObjectId("...")

Voltar

insertOne