AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

ドキュメントの挿入

インスタンスで insert_one() メソッドを呼び出すことで、コレクションにドキュメントを挿入できます。Collection

Collectionインスタンスをパラメータ化したのと同じタイプのドキュメントを挿入する必要があります。 たとえば、 MyStruct構造体でコレクションをパラメータ化した場合、ドキュメントを挿入するには、 MyStructインスタンスをパラメータとしてinsert_one()メソッドに渡します。 型パラメータの指定の詳細については、「 データベースとコレクション 」ガイドの「コレクション パラメータ 」セクションを参照してください。

insert_one() メソッドは、新しく挿入されたドキュメントの _idフィールドを含む InsertOneResult タイプを返します。

insert_one()メソッドについて詳しくは、ドキュメントの挿入ガイドをご覧ください。

この例では、 sample_restaurantsデータベースのrestaurantsコレクションにドキュメントを挿入します。 この例では、コレクション内のドキュメントをモデル化するために、 nameboroughcuisineフィールドを持つRestaurant構造体を使用します。

次のコードではRestaurantインスタンスを作成し、それを コレクションに挿入します。

各実行時に対応するコードを表示するには、 AsynchronousタブまたはSynchronousタブを選択します。

use std::env;
use mongodb::{ bson::doc, Client, Collection };
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
borough: String,
cuisine: String,
name: 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 doc = Restaurant {
name: "Sea Stone Tavern".to_string(),
cuisine: "Greek".to_string(),
borough: "Queens".to_string(),
};
let res = my_coll.insert_one(doc, None).await?;
println!("Inserted a document with _id: {}", res.inserted_id);
Ok(())
}
Inserted a document with _id: ObjectId("...")
use std::env;
use mongodb::{ bson::doc, sync::{ Client, Collection } };
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
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, None)?;
println!("Inserted a document with _id: {}", res.inserted_id);
Ok(())
}
Inserted a document with _id: ObjectId("...")