Overview
このガイドでは、MongoDB コレクションにドキュメントを挿入する方法を学習できます。
MongoDB 内のドキュメントを検索、更新、削除する前に、それらを挿入する必要があります。 次の方法を使用して、ドキュメントを挿入できます。
insert_one()
: 1 つのドキュメントを挿入するinsert_many()
: 1 つ以上のドキュメントを挿入する
このガイドには、次のセクションが含まれています。
_id フィールドは、各ドキュメントに含まれる
_id
フィールドを記述します「ドキュメントの挿入」では、ドライバーを使用して単一のドキュメントをコレクションに挿入する方法について説明します。
「複数のドキュメントの挿入」では、ドライバーを使用して複数のドキュメントをコレクションに挿入する方法について説明します。
追加情報では、このガイドで言及されている型とメソッドのリソースとAPIドキュメントへのリンクを提供します
_id フィールド
MongoDB コレクションでは、各ドキュメントに一意の_id
フィールド値が含まれている必要があります。 ドライバーは、コレクションにデータを挿入すると、各ドキュメントに対して一意の 値をObjectId
型として自動的に生成します。
カスタム値を設定する場合は、挿入操作に渡されるドキュメントの_id
フィールドに値を割り当てられます。
重要
Duplicate _id Values
重複する_id
値を含むドキュメントを挿入しようとすると、それらの値は一意のインデックス制約に違反し、書込み操作が失敗します。
_id
フィールドの詳細については、サーバー マニュアルの「一意のインデックス」を参照してください。
ドキュメント構造とルールの詳細については、サーバー マニュアルのドキュメントを参照してください。
ドキュメントの挿入
単一のドキュメントをコレクションに挿入するには、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, None).await?; println!("Inserted document with _id: {}", insert_one_result.inserted_id);
Inserted document with _id: 8
Tip
存在しないデータベースとコレクション
データベースとコレクションに対して書き込み操作を実行するときに、コレクションが存在しない場合、サーバーはそれらを自動的に作成します。
insert_one の動作を変更する
insert_one()
メソッドの動作を変更するには、 InsertOneOptions
構造体を作成して渡します。
注意
インスタンス化オプション
Rust ドライバーは、 InsertOneOptions
を含む多くのさまざまなタイプを作成するためのビルダ設計パターンを実装します。 各タイプのbuilder()
メソッドを使用して、オプション ビルダー関数を 1 つずつ連鎖させてオプション インスタンスを構築できます。
次の表では、 InsertOneOptions
で利用できるオプションについて説明しています。
オプション | 説明 |
---|---|
| If true , allows the driver to perform a write that violates
document-level validation. To learn more about validation, see
the guide on Schema Validation.Type: bool Default: false |
| The write concern for the operation. If you don't set this
option, the operation inherits the write concern set for
the collection. To learn more about write concerns, see
Write Concern in the
Server manual. Type: WriteConcern |
| An arbitrary Bson value tied to the operation to trace
it through the database profiler, currentOp , and
logs. This option is available only when connecting to
MongoDB Server versions 4.4 and later.Type: Bson Default: None |
次のコードは、 InsertOneOptions
インスタンスを構築する方法を示しています。
let _opts = InsertOneOptions::builder() .bypass_document_validation(true) .build();
複数のドキュメントの挿入
複数のドキュメントをコレクションに挿入するには、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, None).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()
メソッドの動作を変更するには、 InsertManyOptions
構造体を作成して渡します。 次の表では、 InsertManyOptions
で利用できるオプションについて説明しています。
オプション | 説明 |
---|---|
| If true , allows the driver to perform a write that violates
document-level validation. To learn more about validation, see
the guide on Schema Validation.Type: bool Default: false |
| If true , when any insert fails, the operation returns
without inserting the remaining documents. If false , even
if an insert fails, the operation continues with the remaining
writes. To learn more about ordered inserts, see the
Ordered Behavior Example section
of this guide.Type: bool Default: true |
| The write concern for the operation. If you don't set this
option, the operation inherits the write concern set for
the collection. To learn more about write concerns, see
Write Concern in the
Server manual. Type: WriteConcern |
| An arbitrary Bson value tied to the operation to trace
it through the database profiler, currentOp , and
logs. This option is available only when connecting to
MongoDB Server versions 4.4 and later.Type: Bson Default: None |
次のコードは、 InsertManyOptions
インスタンスを構築する方法を示しています。
let _opts = InsertManyOptions::builder() .comment(Some("hello world".into())) .build();
順序付き動作の例
たとえば、次のドキュメントを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" }
これらのドキュメントを挿入しようとすると、結果は、 InsertManyOptions
のordered
オプションの値によって異なります。
ordered
がtrue
(デフォルト値)の場合、ドライバは重複する_id
値を持つドキュメントを挿入しようとするとBulkWriteError
をスローします。 ただし、ドライバーはエラーが発生する前にドキュメントを挿入します。ordered
を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: 4, title: "Blueberries for Sal".to_string(), author: "".to_string() }, Book { _id: 3, title: "Goodnight Moon".to_string(), author: "".to_string() } ]; let opts = InsertManyOptions::builder().ordered(false).build(); my_coll.insert_many(docs, opts).await?;
この操作の結果はBulkWriteError
になりますが、 コレクション内のエラーが発生していないドキュメントを見つけることができます。
{ "_id": 1, "title": "Where the Wild Things Are" } { "_id": 2, "title": "The Very Hungry Caterpillar" } { "_id": 3, "title": "Goodnight Moon" }
詳細情報
挿入操作の実行可能な例については、次の使用例を参照してください。
API ドキュメント
このガイドで言及されているメソッドとタイプの詳細については、次のAPIドキュメントを参照してください。