一括書き込み操作
項目一覧
Overview
このガイドでは、 Scalaドライバーを使用して、1 回のデータベース呼び出しでデータに複数の変更を加える一括書き込み操作を実行する方法を説明します。
同じタスクでドキュメントの挿入、ドキュメントの更新、ドキュメントの削除が必要になる状況を考えてみましょう。 個別の書込みメソッドを使用して各タイプの操作を実行すると、各書込みはデータベースに個別にアクセスします。 一括書き込み操作を使用して、アプリケーションがサーバーに行う呼び出しの数を最適化できます。
サンプル データ
このガイドの例では、restaurants
sample_restaurants
Atlasサンプルデータセット の データベース内の コレクションを使用します。 Scalaアプリケーションからこのコレクションにアクセスするには、AtlasMongoClient
クラスターに接続する を作成し、 変数と 変数に次の値を割り当てます。database
collection
val database: MongoDatabase = mongoClient.getDatabase("sample_restaurants") val collection: MongoCollection[Document] = database.getCollection("restaurants")
MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 「Atlas を使い始める」ガイドを参照してください。
書込み (write) 操作を定義する
実行する書込み操作ごとに、汎用のWriteModel
クラスから継承する次の操作クラスのいずれかの対応するインスタンスを作成します。
InsertOneModel
UpdateOneModel
UpdateManyModel
ReplaceOneModel
DeleteOneModel
DeleteManyModel
次に、これらのインスタンスのリストをbulkWrite()
メソッドに渡します。
次のセクションでは、前述のクラスのインスタンスを作成して使用する方法を示します。 「一括操作の実行 」セクションでは、モデルのリストをbulkWrite()
メソッドに渡して一括操作を実行する方法が説明されています。
挿入操作
挿入操作を実行するには、 InsertOneModel
インスタンスを作成し、挿入するドキュメントを指定します。
次の例では、 InsertOneModel
のインスタンスを作成しています。
val insertOneModel = InsertOneModel( Document("name" -> "Blue Moon Grill", "borough" -> "Brooklyn", "cuisine" -> "American") )
複数のドキュメントを挿入するには、ドキュメントごとにInsertOneModel
のインスタンスを作成します。
重要
一括操作を実行する場合、 InsertOneModel
はコレクション内にすでに存在する_id
を含むドキュメントを挿入できません。 この状況では、ドライバーはMongoBulkWriteException
をスローします。
アップデート操作
ドキュメントを更新するには、 UpdateOneModel
のインスタンスを作成し、次の引数を渡します。
コレクション内のドキュメントをマッチングするために使用される基準を指定するクエリフィルター。
実行する更新操作。更新操作の詳細については、 MongoDB Serverマニュアルの「 フィールド更新演算子 」ガイドを参照してください。
次の例では、 UpdateOneModel
のインスタンスを作成しています。
val updateOneFilter = equal("name", "White Horse Tavern") val updateOneDoc = set("borough", "Queens") val updateOneModel = UpdateOneModel(updateOneFilter, updateOneDoc)
複数のドキュメントが UpdateOneModel
インスタンスで指定されたクエリフィルターに一致する場合、この操作最初の結果が更新されます。次のコードに示すように、ドライバーが 更新操作 を実行する前に、一致したドキュメントに順序を適用するために、UpdateOptions
インスタンスで並べ替えを指定できます。
val options = UpdateOptions.sort(ascending("name"))
複数のドキュメントを更新するには、 UpdateManyModel
のインスタンスを作成し、 UpdateOneModel
と同じ引数を渡します。 UpdateManyModel
クラスは、クエリフィルターに一致するすべてのドキュメントのアップデートを指定します。
次の例では、 UpdateManyModel
のインスタンスを作成しています。
val updateManyFilter = equal("name", "Wendy's") val updateManyDoc = set("cuisine", "Fast food") val updateManyModel = UpdateOneModel(updateManyFilter, updateManyDoc)
置換操作
置換操作、指定されたドキュメントのすべてのフィールドと値が削除され、指定した新しいフィールドと値に置き換えられます。置換操作 を実行するには、ReplaceOneModel
のインスタンスを作成し、次の引数を渡します。
コレクション内のドキュメントをマッチングするために使用される基準を指定するクエリフィルター
挿入する新しいフィールドと値を指定する置換ドキュメント
次の例では、 ReplaceOneModel
のインスタンスを作成しています。
val replaceFilter = equal("name", "Cooper Town Diner") val replaceDoc = Document("name" -> "Smith Town Diner", "borough" -> "Brooklyn", "cuisine" -> "American") val replaceOneModel = ReplaceOneModel(replaceFilter, replaceDoc)
複数のドキュメントが ReplaceOneModel
インスタンスで指定されたクエリフィルターに一致する場合、その操作は最初の結果を置き換えます。次のコードに示すように、ドライバーが置換操作を実行する前に、一致したドキュメントに順序を適用するために、ReplaceOptions
インスタンスで並べ替えを指定できます。
val options = ReplaceOptions.sort(ascending("name"))
Tip
複数のドキュメントの置換
複数のドキュメントを置き換えるには、ドキュメントごとにReplaceOneModel
のインスタンスを作成します。
削除操作
ドキュメントを削除するには、 DeleteOneModel
のインスタンスを作成し、削除するドキュメントを指定するクエリフィルターを渡します。 DeleteOneModel
インスタンスには、クエリフィルターに一致する最初のドキュメントのみを削除するための手順が記載されています。
次の例では、 DeleteOneModel
のインスタンスを作成しています。
val deleteOneModel = DeleteOneModel(equal("name", "Morris Park Bake Shop"))
複数のドキュメントを削除するには、 DeleteManyModel
のインスタンスを作成し、削除するドキュメントを指定してクエリフィルターを渡します。 DeleteManyModel
のインスタンスには、クエリフィルターに一致するすべてのドキュメントを削除するための手順が表示されます。
次の例では、 DeleteManyModel
のインスタンスを作成しています。
val deleteManyModel = DeleteManyModel(equal("cuisine", "Experimental"))
一括操作の実行
実行する操作ごとにモデル インスタンスを定義した後、これらのインスタンスのリストをbulkWrite()
メソッドに渡します。 デフォルトでは、 メソッドはモデルのリストで指定された順序で操作を実行します。
次の例では、 bulkWrite()
メソッドを使用して複数の書込み操作を実行します。
val insertOneModel = InsertOneModel( Document("name" -> "Red's Pizza", "borough" -> "Brooklyn", "cuisine" -> "Pizzeria") ) val updateOneModel = UpdateOneModel(equal("name", "Moonlit Tavern"), set("borough", "Queens")) val deleteManyModel = DeleteManyModel(equal("name", "Crepe")) val writes = Seq(insertOneModel, updateOneModel, deleteManyModel) val observable = collection.bulkWrite(writes) observable.subscribe( (result: BulkWriteResult) => println(s"Success: $result"), (error: Throwable) => println(s"Error: ${error.getMessage}"), () => println("Completed") )
Success: AcknowledgedBulkWriteResult{insertedCount=1, matchedCount=1, removedCount=1, modifiedCount=1, upserts=[], inserts=[BulkWriteInsert{index=0, id=BsonObjectId{value=...}}]} Completed
いずれかの書き込み操作が失敗した場合、 Scalaドライバーは BulkWriteError
を発生させ、それ以上の操作を実行しません。 BulkWriteError
は、失敗した操作と例外に関する詳細を含む details
アイテムを提供します。
注意
ドライバーが一括操作を実行する場合、ターゲット コレクションの書込み保証 (write concern) が使用されます。 ドライバーは、実行順序に関係なく、すべての操作を試行した後にすべての書込み保証 (write concern) エラーを報告します。
一括書き込み操作をカスタマイズする
オプションで、bulkWrite()
メソッドは BulkWriteOptions
パラメータを受け入れます。このパラメータは、 一括書込み操作を構成するために使用できるオプションを指定します。オプションを指定しない場合、ドライバーはデフォルト設定で一括操作を実行します。
次の表では、 BulkWriteOptions
インスタンスを構成するために使用できる setter メソッドについて説明します。
方式 | 説明 |
---|---|
| 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.Defaults to true . |
| Specifies whether the update operation bypasses document validation. This lets you
update documents that don't meet the schema validation requirements, if any
exist. For more information about schema validation, see Schema
Validation in the MongoDB
Server manual. Defaults to false . |
| Sets a comment to attach to the operation. |
| Provides a map of parameter names and values to set top-level
variables for the operation. Values must be constant or closed
expressions that don't reference document fields. |
次のコードでは、オプションを作成し、ordered
オプションを false
に設定して、順序なしの一括書き込みを指定します。次に、この例ではbulkWrite()
メソッドを使用して 一括操作 を実行します。
val options = BulkWriteOptions().ordered(false) val observable = collection.bulkWrite(writes, options)
順序付けなし一括書き込み 内のいずれかの書き込み操作が失敗した場合、 Scalaドライバーはすべての操作を試行した後にのみエラーを報告します。
注意
順序なしの一括操作では、実行順序は保証されません。 この順序は、ランタイムを最適化するために一覧表示する方法とは異なる場合があります。
戻り値
bulkWrite()
メソッドは、BulkWriteResult
を含む SingleObservable
オブジェクトを返します。 Observable にサブスクライブし、次の方法を使用することで、BulkWriteResult
インスタンスからの情報にアクセスできます。
方式 | 説明 |
---|---|
| Indicates if the server acknowledged the write operation. |
| The number of documents deleted, if any. |
| The number of documents inserted, if any. |
| The list of inserted documents, if any. |
| The number of documents matched for an update, if applicable. |
| The number of documents modified, if any. |
| The list of upserted documents, if any. |
詳細情報
個々の書込み操作を実行する方法については、次のガイドを参照してください。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。