ドキュメントの挿入
コレクションにドキュメントを挿入するには、 insert_one() メソッド を呼び出しますCollection
インスタンスのメソッドです。
Collection
インスタンスをパラメータ化したのと同じタイプのドキュメントを挿入する必要があります。 たとえば、 MyStruct
構造体でコレクションをパラメータ化した場合、ドキュメントを挿入するには、 MyStruct
インスタンスをパラメータとしてinsert_one()
メソッドに渡します。 型パラメータの指定の詳細については、データベースとコレクション ガイドのコレクション パラメータ指定 セクションを参照してください。
insert_one()
メソッドは InsertOneResult _id
を返します 新しく挿入されたドキュメントの フィールドを含む 型。
insert_one()
メソッドについて詳しくは、ドキュメントの挿入ガイドをご覧ください。
例
この例では、 sample_restaurants
データベースのrestaurants
コレクションにドキュメントを挿入します。 この例では、コレクション内のドキュメントをモデル化するために、 name
、 borough
、 cuisine
フィールドを持つRestaurant
構造体を使用します。
次のコードではRestaurant
インスタンスを作成し、それを コレクションに挿入します。
AsynchronousSynchronous各実行時に対応するコードを表示するには、 タブまたは タブを選択します。
use std::env; use mongodb::{ bson::doc, 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?; let my_coll: Collection<Restaurant> = client .database("sample_restaurants") .collection("restaurants"); let doc = Restaurant { name: "Sea Stone Tavern".to_string(), cuisine: "Greek".to_string(), borough: "Queens".to_string(), }; let res = my_coll.insert_one(doc).await?; println!("Inserted a document with _id: {}", res.inserted_id); Ok(()) }
use std::env; use mongodb::{ bson::doc, 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)?; let my_coll: Collection<Restaurant> = client .database("sample_restaurants") .collection("restaurants"); let doc = Restaurant { name: "Sea Stone Tavern".to_string(), cuisine: "Greek".to_string(), borough: "Queens".to_string(), }; let res = my_coll.insert_one(doc).run()?; println!("Inserted a document with _id: {}", res.inserted_id); Ok(()) }