Overview
このガイドでは、 Rubyドライバーを使用して、削除操作を実行し、 MongoDBコレクションからドキュメントを削除する方法を学習できます。
削除操作は、MongoDB コレクションから 1 つ以上のドキュメントを削除します。 削除操作は、 delete_one
またはdelete_many
メソッドを使用して実行できます。
サンプル データ
このガイドの例では、 Atlasサンプルデータセット の sample_restaurants
データベースの restaurants
コレクションを使用します。Rubyアプリケーションからこのコレクションにアクセスするには、Atlas クラスターに接続する Mongo::Client
オブジェクトを作成し、次の値を database
変数と collection
変数に割り当てます。
database = client.use('sample_restaurants') collection = database[:restaurants]
MongoDB Atlasクラスターを無料で作成して、サンプルデータセットをロードする方法については、 「Atlas を使い始める」ガイドを参照してください。
削除操作
MongoDB では、次の方法で削除操作を実行できます。
delete_one
は、検索条件に一致する最初のドキュメントを削除します。delete_many
は、検索条件に一致するすべてのドキュメントを削除します
各削除メソッドにはクエリフィルターパラメーターが必要です。このパラメーターは、削除対象として選択するドキュメントを決定する検索条件を指定します。クエリフィルターの詳細については、クエリの指定ガイドをご覧ください。
単一ドキュメントの削除
次の例では、 delete_one
メソッドを使用して、 name
フィールドの値が"Happy Garden"
であるドキュメントを削除します。
filter = { name: 'Happy Garden' } result = collection.delete_one(filter) puts "Deleted #{result.deleted_count} document(s)"
Deleted 1 document(s)
複数のドキュメントの削除
次の例では、 delete_many
メソッドを使用して、 borough
フィールドの値が"Brooklyn"
で、かつname
フィールドの値が"Starbucks"
であるすべてのドキュメントを削除します。
filter = { name: 'Starbucks', borough: 'Brooklyn' } result = collection.delete_many(filter) puts "Deleted #{result.deleted_count} document(s)"
Deleted 3 document(s)
削除操作をカスタマイズする
削除操作を構成するオプションを設定するには、Hash
オブジェクトをdelete_one
メソッドと delete_many
メソッドにパラメーターとして渡します。オプションを指定しない場合、ドライバーはデフォルト設定で削除操作を実行します。
次の表では、削除操作を構成するために使用できるオプションについて説明します。
オプション | 説明 |
---|---|
| Specifies the kind of language collation to use when sorting
results. For more information, see Collation
in the MongoDB Server manual. |
| Specifies the session to use for the operation. To learn more about sessions, see
Client Sessions and Causal Consistency Guarantees
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. |
| 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. |
変更削除の例
次のコードでは、hint
オプションを指定して、削除操作に"name_index"
インデックスを使用するように指示します。次に、この例ではdelete_many
メソッドを使用して、string "Red"
を含む name
フィールド値を持つ restaurants
コレクション内のすべてのドキュメントを削除します。
filter = { name: /Red/ } options = { hint: 'name_index' } result = collection.delete_many(filter, options) puts "Deleted #{result.deleted_count} document(s)"
Deleted 124 document(s)
Tip
前述の例でdelete_many
メソッドではなくdelete_one
メソッドを使用すると、ドライバーはクエリフィルターに一致する最初のドキュメントのみを削除します。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。