Overview
このガイドでは、MongoDB コレクションにドキュメントを挿入する方法を学習できます。
MongoDB 内のドキュメントを検索、更新、削除する前に、それらを挿入する必要があります。 次の方法を使用して、ドキュメントを挿入できます。
insert_one(): 1 つのドキュメントを挿入するinsert_many(): 1 つ以上のドキュメントを挿入する
このガイドには、次のセクションが含まれています。
_id フィールドは、各ドキュメントに含まれる
_idフィールドを記述します「ドキュメントの挿入」では、ドライバーを使用して単一のドキュメントをコレクションに挿入する方法について説明します。
「複数のドキュメントの挿入」では、ドライバーを使用して複数のドキュメントをコレクションに挿入する方法について説明します。
追加情報では、このガイドで言及されている型とメソッドのリソースとAPIドキュメントへのリンクを提供します
_id フィールド
MongoDB コレクションでは、各ドキュメントに一意の_idフィールド値が含まれている必要があります。 ドライバーは、コレクションにデータを挿入すると、各ドキュメントに対して一意の 値をObjectId型として自動的に生成します。
カスタム値を設定する場合は、挿入操作に渡されるドキュメントの_idフィールドに値を割り当てられます。
重要
Duplicate _id Values
重複する_id値を含むドキュメントを挿入しようとすると、それらの値は一意のインデックス制約に違反し、書込み操作が失敗します。
_idフィールドの詳細については、サーバー マニュアルの「一意のインデックス」を参照してください。
ドキュメント構造とルールの詳細については、サーバー マニュアルのドキュメントを参照してください。
ドキュメントの挿入
単一のドキュメントをコレクションに挿入するには、insert_one() メソッドを使用します。
Collectionインスタンスをパラメータ化したのと同じタイプのドキュメントを挿入する必要があります。 たとえば、 MyStruct構造体でコレクションをパラメータ化した場合、ドキュメントを挿入するには、 MyStructインスタンスをパラメータとしてinsert_one()メソッドに渡します。 型パラメータの指定の詳細については、「 データベースとコレクション 」ガイドの「コレクション パラメータ 」セクションを参照してください。
挿入に成功すると、メソッドは、新しく挿入されたドキュメントの_idフィールドを含むInsertOneResultタイプを返します。
例
次の例では、 insert_one()メソッドを使用してbooksコレクションにドキュメントを挿入しています。
let my_coll: Collection<Book> = client.database("db").collection("books"); let doc = Book { _id: 8, title: "Atonement".to_string(), author: "Ian McEwan".to_string() }; let insert_one_result = my_coll.insert_one(doc).await?; println!("Inserted document with _id: {}", insert_one_result.inserted_id);
Inserted document with _id: 8
Tip
存在しないデータベースとコレクション
データベースとコレクションに対して書き込み操作を実行するときに、コレクションが存在しない場合、サーバーはそれらを自動的に作成します。
insert_one の動作を変更する
オプション ビルダー メソッドをinsert_one()に連鎖させることで、 insert_one()メソッドの動作を変更できます。 これらのオプション ビルダー メソッドはInsertOneOptions構造体フィールドを設定します。
注意
設定オプション
オプション ビルダのメソッドをinsert_one()メソッド呼び出しに直接連鎖させることで、 InsertOneOptionsフィールドを設定できます。 以前のバージョンのドライバーを使用している場合は、オプション ビルダのメソッドをbuilder()メソッドに連結してInsertOneOptionsインスタンスを構築する必要があります。 次に、オプション インスタンスをパラメーターとしてinsert_one()に渡します。
次の表では、 InsertOneOptionsで利用できるオプションについて説明しています。
オプション | 説明 |
|---|---|
|
|
| 操作の書込み保証 (write concern) 。このオプションを設定しない場合、操作はコレクションに設定された書込み保証 (write concern)を継承します。書込み保証 (write concern) の詳細については、サーバー マニュアルの「 書込み保証 (write concern) |
|
|
次のコードは、 bypass_document_validation()メソッドをinsert_one()メソッドに連結してbypass_document_validationフィールドを設定する方法を示しています。
let _result = my_coll.insert_one(doc) .bypass_document_validation(true) .await?;
完全なファイルの例: 1 つのドキュメントの挿入
この例では、 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("...")
複数のドキュメントの挿入
複数のドキュメントをコレクションに挿入するには、insert_many() メソッドを使用します。
1 つ以上のドキュメントを含むベクトルをinsert_many()メソッドに渡して、コレクションに挿入します。 These documents must be instances of the type that you parameterized your Collection instance with. たとえば、コレクションをMyStruct構造体でパラメーター化した場合は、 MyStructインスタンスのベクトルをinsert_many()メソッドのパラメーターとして渡します。
挿入に成功すると、 メソッドは挿入されたドキュメントの _id 値を参照する InsertManyResult 型を返します。
例
次の例では、 insert_many()メソッドを使用して複数のドキュメントをbooksコレクションに挿入しています。
let docs = vec![ Book { _id: 5, title: "Cat's Cradle".to_string(), author: "Kurt Vonnegut Jr.".to_string() }, Book { _id: 6, title: "In Memory of Memory".to_string(), author: "Maria Stepanova".to_string() }, Book { _id: 7, title: "Pride and Prejudice".to_string(), author: "Jane Austen".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); }
Inserted documents with _ids: Int32(5) Int32(6) Int32(7)
Tip
存在しないデータベースとコレクション
データベースとコレクションに対して書き込み操作を実行するときに、コレクションが存在しない場合、サーバーはそれらを自動的に作成します。
insert_many の動作の変更
オプション ビルダー メソッドをinsert_many()に連鎖させることで、 insert_many()メソッドの動作を変更できます。 これらのオプション ビルダー メソッドはInsertManyOptions構造体フィールドを設定します。
次の表では、 InsertManyOptionsで利用できるオプションについて説明しています。
オプション | 説明 |
|---|---|
|
|
|
|
| 操作の書込み保証 (write concern) 。このオプションを設定しない場合、操作はコレクションに設定された書込み保証 (write concern)を継承します。書込み保証 (write concern) の詳細については、サーバー マニュアルの「 書込み保証 (write concern) |
|
|
次のコードは、 comment()メソッドをinsert_many()メソッドに連結してcommentフィールドを設定する方法を示しています。
let _result = my_coll.insert_many(docs) .comment(Some("hello world".into())) .await?;
完全なファイルの例: 複数のドキュメントの挿入
この例では、 sample_restaurantsデータベースの restaurantsコレクションに複数のドキュメントを挿入します。 この例では、ドキュメントのベクトルを insert_many() メソッドに渡すことで、name と cuisineフィールド値を持つドキュメントを挿入します。
これらのドキュメントは、Document 型またはカスタムデータ型のインスタンスとして挿入できます。 コレクションのデータを表すデータ型を指定するには、強調表示された行に対して次のアクションを実行します。
コレクションドキュメントをBSONドキュメントとしてアクセスして挿入するには、
<T>型パラメータを<Document>に置き換え、<struct or doc>プレースホルダーをinsert_docsに置き換えます。Restaurant構造体のインスタンスとしてコレクションドキュメントにアクセスして挿入するには、<T>型パラメータを<Restaurant>に置き換え、<struct or doc>プレースホルダーをinsert_structsに置き換えます。Restaurant構造体は、コードファイルの上部で定義されています。
各実行時に対応するコードを表示するには、 AsynchronousタブまたはSynchronousタブを選択します。
use mongodb::{ bson::{doc, Document}, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: 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_docs = vec! [ doc! { "name": "While in Kathmandu", "cuisine": "Nepalese", }, doc! { "name": "Cafe Himalaya", "cuisine": "Nepalese", } ]; let insert_structs = vec! [ Restaurant { name: "While in Kathmandu".to_string(), cuisine: "Nepalese".to_string(), }, Restaurant { name: "Cafe Himalaya".to_string(), cuisine: "Nepalese".to_string(), } ]; // Replace <structs or docs> with the insert_structs or insert_docs variable let insert_many_result = my_coll.insert_many(<structs or 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, Document}, sync::{Client, Collection} }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: 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_docs = vec! [ doc! { "name": "While in Kathmandu", "cuisine": "Nepalese", }, doc! { "name": "Cafe Himalaya", "cuisine": "Nepalese", } ]; let insert_structs = vec! [ Restaurant { name: "While in Kathmandu".to_string(), cuisine: "Nepalese".to_string(), }, Restaurant { name: "Cafe Himalaya".to_string(), cuisine: "Nepalese".to_string(), } ]; // Replace <structs or docs> with the insert_structs or insert_docs variable let insert_many_result = my_coll.insert_many(<structs or 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("...")
順序付き動作の例
たとえば、次のドキュメントをbooksコレクションに挿入するとします。
{ "_id": 1, "title": "Where the Wild Things Are" } { "_id": 2, "title": "The Very Hungry Caterpillar" } { "_id": 1, "title": "Blueberries for Sal" } { "_id": 3, "title": "Goodnight Moon" }
これらのドキュメントを挿入しようとすると、結果は、 ordered()オプション ビルダ メソッドに渡される 値によって異なります。
true(デフォルト値)の値を渡すと、ドライバは重複した_id値を持つドキュメントを挿入しようとするとBulkWriteErrorをスローします。 ただし、ドライバーはエラーが発生する前にドキュメントを挿入します。falseの値を渡した場合でも、重複する_id値を持つドキュメントを挿入しようとしても、ドライバーはBulkWriteErrorをスローしますが、他のすべてのドキュメントが挿入されます。
次のコードは、順序なし書込み操作を実行して前述のドキュメントを挿入する方法を示しています。
let docs = vec![ Book { _id: 1, title: "Where the Wild Things Are".to_string(), author: "".to_string() }, Book { _id: 2, title: "The Very Hungry Caterpillar".to_string(), author: "".to_string() }, Book { _id: 1, title: "Blueberries for Sal".to_string(), author: "".to_string() }, Book { _id: 3, title: "Goodnight Moon".to_string(), author: "".to_string() } ]; my_coll.insert_many(docs).ordered(false).await?;
この操作の結果はBulkWriteErrorになりますが、 コレクション内のエラーが発生していないドキュメントを見つけることができます。
{ "_id": 1, "title": "Where the Wild Things Are" } { "_id": 2, "title": "The Very Hungry Caterpillar" } { "_id": 3, "title": "Goodnight Moon" }
詳細情報
挿入操作の実行可能な例については、次の使用例を参照してください。
API ドキュメント
このガイドで言及されているメソッドとタイプの詳細については、次のAPIドキュメントを参照してください。