Overview
このガイドでは、MongoDB コレクションにドキュメントを挿入する方法を学習できます。
MongoDB 内のドキュメントを検索、更新、削除する前に、それらを挿入する必要があります。 次の方法を使用して、ドキュメントを挿入できます。
insert_one(): 1 つのドキュメントを挿入するinsert_many(): 1 つ以上のドキュメントを挿入する
このガイドには、次のセクションが含まれています。
_id フィールドは、各ドキュメントに含まれる
_idフィールドを記述します「ドキュメントの挿入」では、ドライバーを使用して単一のドキュメントをコレクションに挿入する方法について説明します。
「複数のドキュメントの挿入」では、ドライバーを使用して複数のドキュメントをコレクションに挿入する方法について説明します。
追加情報では、このガイドで言及されている型とメソッドのリソースとAPIドキュメントへのリンクを提供します
_id フィールド
In MongoDB, each document must contain a unique _id field. MongoDB では、このフィールドを次の方法で管理できます。
このフィールドを自分で管理し、設定する各
_id値が一意であることを確認します。ドライバーが一意の
ObjectId値を自動的に生成できるようにします。 挿入を実行するときに_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: boolDefault: 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: BsonDefault: 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: boolDefault: 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: boolDefault: 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: BsonDefault: 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ドキュメントを参照してください。