Overview
このガイドでは、 .NET/ C#ドライバーを使用して一括書込み操作を実行する方法を学習できます。一括書き込み操作を使用すると、データベースへの呼び出しで複数の書き込み操作を実行できます。
同じタスクでドキュメントの挿入、ドキュメントの更新、ドキュメントの削除が必要になる状況を考えてみましょう。 個別の書込みメソッドを使用して各タイプの操作を実行すると、各書込みはデータベースに個別にアクセスします。 一括書き込み操作を使用して、アプリケーションがサーバーに行う呼び出しの数を最適化できます。
IMongoCollection.BulkWrite()
メソッドまたは IMongoCollection.BulkWriteAsync()
メソッドを使用して、単一のコレクションに対して一括書き込み操作を実行できます。各メソッドは、実行する書込み操作を記述する WriteModel<TDocument>
インスタンスのリストを受け取ります。
サンプル データ
このガイドの例では、sample_restaurants.restaurants
Atlasサンプルデータセット の コレクションを使用します。無料のMongoDB Atlasクラスターを作成し、サンプルデータセットをロードする方法については、 クイック スタート チュートリアルを参照してください。
書込み (write) 操作を定義する
実行する書込み操作ごとに、次のいずれかの WriteModel<TDocument>
クラスのインスタンスを作成します。
DeleteManyModel<TDocument>
DeleteOneModel<TDocument>
InsertOneModel<TDocument>
ReplaceOneModel<TDocument>
UpdateManyModel<TDocument>
UpdateOneModel<TDocument>
以下のセクションでは、前述のクラスのインスタンスを作成し、使用して、対応する書込み操作を一括書込み操作で実行する方法を示します。
Tip
POCO を使用した一括書き込み操作
このガイドの例では、すべてのジェネリック クラスの TDocument
型の BsonDocument
型を使用します。これらのクラスには Plain Old CLR Object(POCO) を使用することもできます。 そのためには、コレクション内のドキュメントを表すクラスを定義する必要があります。 クラスには、ドキュメント内のフィールドと一致するプロパティが必要です。 詳しくは、「 POCO 」を参照してください。
挿入操作
挿入操作を実行するには、 InsertOneModel<TDocument>
インスタンスを作成し、挿入するドキュメントを指定します。
次の例では、InsertOneModel<BsonDocument>
クラスのインスタンスを作成しています。このインスタンスは、"name"
フィールドが "Mongo's Deli"
であるドキュメントを restaurants
コレクションに挿入するようにドライバーに指示します。
var insertOneModel = new InsertOneModel<BsonDocument>( new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } );
複数のドキュメントを挿入するには、ドキュメントごとにInsertOneModel<TDocument>
のインスタンスを作成します。
重要
重複キー エラー
一括操作を実行する場合、 InsertOneModel<TDocument>
はコレクション内にすでに存在する_id
を含むドキュメントを挿入できません。 この状況では、ドライバーはMongoBulkWriteException
をスローします。
アップデート操作
単一のドキュメントを更新するには、UpdateOneModel<TDocument>
のインスタンスを作成し、次の引数を渡します。
コレクション内のドキュメントをマッチングするために使用される基準を指定する クエリフィルター 。クエリの指定の詳細については、 MongoDB Serverマニュアルのクエリ演算子とプロジェクション 演算子を参照してください。
実行する更新を説明する更新ドキュメント。更新を指定する方法の詳細については、 MongoDB Serverマニュアルの更新演算子を参照してください。
UpdateOneModel<TDocument>
インスタンスは、クエリフィルターに一致する最初のドキュメントの更新を指定します。
次の コード例では、UpdateOneModel<BsonDocument>
オブジェクトは restaurants
コレクションの更新操作を表しています。この操作は、name
フィールドの値が "Mongo's Deli"
であるコレクション内の最初のドキュメントと一致します。次に、一致したドキュメントの cuisine
フィールドの値を "Sandwiches and Salads"
にアップデートします。
var updateOneModel = new UpdateOneModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") );
複数のドキュメントを更新するには、 UpdateManyModel<TDocument>
のインスタンスを作成し、 UpdateOneModel<TDocument>
と同じ引数を渡します。 UpdateManyModel<TDocument>
クラスは、クエリフィルターに一致するすべてのドキュメントのアップデートを指定します。
次の コード例では、UpdateManyModel<BsonDocument>
オブジェクトは restaurants
コレクションの更新操作を表しています。この操作は、name
フィールドの値が "Mongo's Deli"
であるコレクション内のすべてのドキュメントと一致します。次に、cuisine
フィールドの値を "Sandwiches and Salads"
にアップデートします。
var updateManyModel = new UpdateManyModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") );
置換操作
置換操作により、指定されたドキュメントのすべてのフィールドと値が削除され、指定した新しいフィールドと値に置き換えられます。 置換操作を実行するには、 ReplaceOneModel<TDocument>
のインスタンスを作成し、クエリフィルターと、一致するドキュメントを置き換えるフィールドと値を渡します。
次の例では、ReplaceOneModel<BsonDocument>
オブジェクトは restaurants
コレクションに対する置換操作を表しています。この操作は、restaurant_id
フィールドの値が "1234"
であるコレクション内のドキュメントと一致します。次に、このドキュメントから _id
以外のすべてのフィールドを削除し、name
、cuisine
、borough
、restaurant_id
フィールドに新しい値を設定します。
var replaceOneModel = new ReplaceOneModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("restaurant_id", "1234"), new BsonDocument{ { "name", "Mongo's Pizza" }, { "cuisine", "Pizza" }, { "borough", "Brooklyn" }, { "restaurant_id", "5678" } } );
複数のドキュメントを置き換えるには、ドキュメントごとにReplaceOneModel<TDocument>
のインスタンスを作成する必要があります。
削除操作
ドキュメントを削除するには、 DeleteOneModel<TDocument>
のインスタンスを作成し、削除するドキュメントを指定するクエリフィルターを渡します。 DeleteOneModel<TDocument>
インスタンスには、クエリフィルターに一致する最初のドキュメントのみを削除するための手順が記載されています。
次のコード例では、DeleteOneModel<BsonDocument>
オブジェクトは restaurants
コレクションの削除操作を表しています。この操作は、restaurant_id
フィールドの値が "5678"
である最初のドキュメントを一致させ、削除します。
var deleteOneModel = new DeleteOneModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("restaurant_id", "5678") );
複数のドキュメントを削除するには、DeleteManyModel<TDocument>
のインスタンスを作成し、削除するドキュメントを指定してクエリフィルターを渡します。DeleteManyModel<TDocument>
のインスタンスには、 クエリフィルターに一致するすべてのドキュメントを削除するための手順が表示されます。
次のコード例では、DeleteManyModel<BsonDocument>
オブジェクトは restaurants
コレクションの削除操作を表しています。この操作は、name
フィールドの値が "Mongo's Deli"
であるすべてのドキュメントを照合して削除します。
var deleteManyModel = new DeleteManyModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli") );
一括操作の実行
実行する操作ごとに WriteModel
インスタンスを定義したら、IEnumerable
インターフェースを実装するクラスのインスタンスを作成します。この IEnumerable
に WriteModel
オブジェクトを追加し、IEnumerable
を BulkWrite()
または BulkWriteAsync()
メソッドに渡します。デフォルトでは 、これらのメソッドはリストで定義されている順序で操作を実行します。
Tip
IEnumerable
Array
と List
は、IEnumerable
インターフェースを実装する 2 つの一般的なクラスです。
同期 BulkWrite()
メソッドと非同期 BulkWriteAsync()
メソッドを使用して、restaurants
コレクションで一括書込み操作を実行する方法を表示するには、次のタブから を選択します。
var models = new List<WriteModel<BsonDocument>> { new InsertOneModel<BsonDocument>( new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } ), new InsertOneModel<BsonDocument>( new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Brooklyn" }, { "restaurant_id", "5678" } } ), new UpdateManyModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") ), new DeleteOneModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("restaurant_id", "1234") ) }; var results = collection.BulkWrite(models); Console.WriteLine(results);
var models = new List<WriteModel<BsonDocument>> { new InsertOneModel<BsonDocument>( new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Manhattan" }, { "restaurant_id", "1234" } } ), new InsertOneModel<BsonDocument>( new BsonDocument{ { "name", "Mongo's Deli" }, { "cuisine", "Sandwiches" }, { "borough", "Brooklyn" }, { "restaurant_id", "5678" } } ), new UpdateManyModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("name", "Mongo's Deli"), Builders<BsonDocument>.Update.Set("cuisine", "Sandwiches and Salads") ), new DeleteOneModel<BsonDocument>( Builders<BsonDocument>.Filter.Eq("restaurant_id", "1234") ) }; var results = await collection.BulkWriteAsync(models); Console.WriteLine(results);
上記のコード例では、次の出力が生成されます。
MongoDB.Driver.BulkWriteResult1+Acknowledged[MongoDB.Bson.BsonDocument]
注意
ドライバーが一括操作を実行する場合、ターゲット コレクションの書込み保証 (write concern) が使用されます。 ドライバーは、実行順序に関係なく、すべての操作を試行した後にすべての書込み保証 (write concern) エラーを報告します。
一括書き込み操作をカスタマイズ
BulkWrite()
または BulkWriteAsync()
メソッドを呼び出すと、BulkWriteOptions
クラスのインスタンスを渡すことができます。BulkWriteOptions
クラスには、 一括書込み操作を構成するために使用できるオプションを表す次のプロパティが含まれています。
プロパティ | 説明 |
---|---|
| Specifies whether the operation bypasses document-level validation. For more
information, see Schema
Validation in the MongoDB Server
manual. Defaults to False . |
| A comment to attach to the operation, in the form of a BsonValue . For
more information, see the delete command
fields guide in the
MongoDB Server manual. |
| If True , the driver performs the write operations in the order
provided. If an error occurs, the remaining operations are not
attempted.If False , the driver performs the operations in an
arbitrary order and attempts to perform all operations. If any of the write
operations in an unordered bulk write fail, the driver
reports the errors only after attempting all operations.Defaults to True . |
| A map of parameter names and values, in the form of a BsonDocument . Values
must be constant or closed
expressions that don't reference document fields. For more information,
see the let statement in the
MongoDB Server manual. |
次のコード例では、BulkWriteOptions
オブジェクトを使用して順序なしの一括書込み操作を実行しています。
戻り値
BulkWrite()
メソッドと BulkWriteAsync()
メソッドは、次のプロパティを含む BulkWriteResult
オブジェクトを返します。
プロパティ | 説明 |
---|---|
| Indicates whether the server acknowledged the bulk write operation. If the
value of this property is False and you try to access any other property
of the BulkWriteResult object, the driver throws an exception. |
| The number of documents deleted, if any. |
| The number of documents inserted, if any. |
| The number of documents matched for an update, if applicable. |
| The number of documents modified, if any. |
| Indicates whether the modified count is available. |
| A list that contains information about each request that
resulted in an upsert operation. |
| The number of requests in the bulk operation. |
例外の処理
一括書き込み操作のいずれかの操作が失敗した場合、 .NET/ C#ドライバーは BulkWriteError
をスローし、それ以上の操作を実行しません。
BulkWriteError
オブジェクトには、エラーを発生させたリクエストのインデックスを記述する Index
プロパティが含まれています。
詳細情報
個々の書込み操作を実行する方法については、次のガイドを参照してください。
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。