Overview
このガイドでは、 Scalaドライバーを使用して、 削除操作 を実行し、 MongoDBコレクションからドキュメントを削除する方法を学習できます。
削除操作は、MongoDB コレクションから 1 つ以上のドキュメントを削除します。 削除操作は、 deleteOne()またはdeleteMany()メソッドを使用して実行できます。
サンプル データ
このガイドの例では、restaurants sample_restaurantsAtlasサンプルデータセット の データベースの コレクションを使用します。Scalaアプリケーションからこのコレクションにアクセスするには、Atlas クラスターに接続する MongoClient を作成し、database 変数と collection 変数に次の値を割り当てます。
val database: MongoDatabase = mongoClient.getDatabase("sample_restaurants") val collection: MongoCollection[Document] = database.getCollection("restaurants")
MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 「Atlas を使い始める」ガイドを参照してください。
削除操作
MongoDB では、次の方法で削除操作を実行できます。
deleteOne()は、検索条件に一致する最初のドキュメントを削除します。deleteMany()は、検索条件に一致するすべてのドキュメントを削除します
各削除メソッドにはクエリフィルタードキュメント が必要です。このドキュメントは、削除対象として選択するドキュメントを決定する検索条件を指定します。 クエリフィルターの詳細については、「 クエリの指定」ガイドを参照してください。
単一ドキュメントの削除
次の例では、 deleteOne()メソッドを使用して、 nameフィールドの値が"Happy Garden"であるドキュメントを削除します。
val filter = equal("name", "Happy Garden") val observable: Observable[DeleteResult] = collection.deleteOne(filter) observable.subscribe(new Observer[DeleteResult] { override def onNext(result: DeleteResult): Unit = println(s"Deleted document count: ${result.getDeletedCount}") override def onError(e: Throwable): Unit = println(s"Error: $e") override def onComplete(): Unit = println("Completed") })
Deleted document count: 1 Completed
複数のドキュメントの削除
次の例では、 deleteMany()メソッドを使用して、 boroughフィールドの値が"Brooklyn"で、かつnameフィールドの値が"Starbucks"であるすべてのドキュメントを削除します。
val filter = and( equal("borough", "Brooklyn"), equal("name", "Starbucks") ) val observable: Observable[DeleteResult] = collection.deleteMany(filter) observable.subscribe(new Observer[DeleteResult] { override def onNext(result: DeleteResult): Unit = println(s"Deleted document count: ${result.getDeletedCount}") override def onError(e: Throwable): Unit = println(s"Error: $e") override def onComplete(): Unit = println("Completed") })
Deleted document count: 3 Completed
削除操作をカスタマイズする
deleteOne()メソッドとdeleteMany()メソッドはオプションで、削除操作を構成するために使用できるオプションを表すDeleteOptionsパラメータを受け入れます。 オプションを指定しない場合、ドライバーはデフォルト設定で削除操作を実行します。
次の表では、 DeleteOptionsインスタンスを構成するために使用できる setter メソッドについて説明します。
方式 | 説明 |
|---|---|
| Specifies the kind of language collation to use when sorting
results. For more information, see Collation
in the MongoDB Server manual. |
| Specifies the index to use when matching documents.
For more information, see the hint
option in the delete reference page of the MongoDB Server manual. |
| Specifies the index as a string to use when matching documents.
For more information, see the hint
option in the `` delete`` reference page of the MongoDB Server manual. |
| 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. For more information,
see the let option in the delete
reference page of the MongoDB Server manual. |
| Sets a comment to attach to the operation. For more
information, see the Command
Fields section in the delete
reference page of the MongoDB Server manual. |
変更削除の例
次のコードでは、オプションを作成し、 comment()メソッドを使用して削除操作にコメントを追加します。 次に、この例ではdeleteMany()メソッドを使用して、 nameフィールドの値に string "Red"が含まれるrestaurantsコレクション内のすべてのドキュメントを削除します。
val filter = regex("name", "Red") val opts = DeleteOptions().comment("sample comment") val observable = collection.deleteMany(filter, opts) observable.subscribe(new Observer[DeleteResult] { override def onNext(result: DeleteResult): Unit = println(s"Deleted document count: ${result.getDeletedCount}") override def onError(e: Throwable): Unit = println(s"Error: $e") override def onComplete(): Unit = println("Completed") })
Deleted document count: 124 Completed
Tip
前述の例でdeleteMany()メソッドではなくdeleteOne()メソッドを使用すると、ドライバーはクエリフィルターに一致する最初のドキュメントのみを削除します。
戻り値
deleteOne()メソッドとdeleteMany()メソッドはそれぞれDeleteResultインスタンスを返します。 DeleteResultインスタンスから次の情報にアクセスできます。
deletedCountは、削除されたドキュメントの数を示しますwasAcknowledged()は、サーバーが結果を確認した場合にtrueを返します。
クエリフィルターがどのドキュメントにも一致しない場合、ドライバーはドキュメントを削除せず、deletedCount の値は 0 です。
注意
wasAcknowledged()メソッドがfalseを返す場合、 deletedCountプロパティにアクセスしようとするとInvalidOperation例外が発生します。 サーバーが書込み (write) 操作を確認しない場合、ドライバーはこれらの値を決定できません。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。