複数のドキュメントの削除
インスタンスで delete_many() Collection
メソッドを呼び出すと、1 回の操作でコレクションから複数のドキュメントを削除できます。
コレクション内でフィルターに一致するドキュメントを削除するには、 クエリフィルター をdelete_many()
メソッドに渡します。 フィルターを含めない場合、MongoDB はコレクション内のすべてのドキュメントを削除します。
delete_many()
メソッドは DeleteResult を返します 型。このタイプには、削除されたドキュメントの合計数など、削除操作に関する情報が含まれます。
削除操作の詳細については、 ドキュメントの削除のガイドを参照してください。
Tip
コレクション内のすべてのドキュメントを削除するには、 Collection
インスタンスでdrop()
メソッドを呼び出すことを検討してください。 drop()
メソッドの詳細については、「 データベースとコレクション 」ガイドの「コレクションの削除 」セクションを参照してください。
例
この例では、 sample_restaurants
データベース内の restaurants
コレクションからクエリフィルターに一致するすべてのドキュメントを削除します。 delete_many()
メソッドは、borough
フィールドの値が "Manhattan"
で、かつ address.street
フィールドの値が "Broadway"
であるドキュメントを削除します。
restaurants
コレクション内のドキュメントには、Document
型またはカスタムデータ型のインスタンスとしてアクセスできます。 コレクションのデータを表すデータ型を指定するには、強調表示された行の <T>
型パラメータを次のいずれかの値に置き換えます。
<Document>
:コレクションドキュメントはBSONドキュメントとしてアクセスします<Restaurant>
: コードの上部で定義されたRestaurant
構造体のインスタンスとしてコレクションドキュメントにアクセスします
AsynchronousSynchronous各実行時に対応するコードを表示するには、 タブまたは タブを選択します。
use mongodb::{ bson::{ Document, doc }, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Address { street: String, city: String, } struct Restaurant { name: String, borough: String, address: Address, } async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let filter = doc! { "$and": [ doc! { "borough": "Manhattan" }, doc! { "address.street": "Broadway" } ] }; let result = my_coll.delete_many(filter).await?; println!("Deleted documents: {}", result.deleted_count); Ok(()) }
// Your values might differ Deleted documents: 615
use mongodb::{ bson::{ Document, doc }, sync::{ Client, Collection } }; use serde::{ Deserialize, Serialize }; struct Address { street: String, city: String, } struct Restaurant { name: String, borough: String, address: Address, } fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let filter = doc! { "$and": [ doc! { "borough": "Manhattan" }, doc! { "address.street": "Broadway" } ] }; let result = my_coll.delete_many(filter).run()?; println!("Deleted documents: {}", result.deleted_count); Ok(()) }
// Your values might differ Deleted documents: 615