Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Ruby ドライバー
/

Delete Documents

このガイドでは、 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 メソッドにパラメーターとして渡します。オプションを指定しない場合、ドライバーはデフォルト設定で削除操作を実行します。

次の表では、削除操作を構成するために使用できるオプションについて説明します。

オプション
説明

collation

Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.

session

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.

hint

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.

let

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 ドキュメントを参照してください。

戻る

Update Documents

項目一覧