コレクションからドキュメントを削除するには、 インスタンスで delete_one() Collection
メソッドを呼び出します。
delete_one()
コレクションから削除するドキュメントに一致するようにクエリフィルターを メソッドに渡します。クエリフィルターに一致するドキュメントが複数ある場合、 MongoDB はデータベース内の自然な順序に従って、または DeleteOptionsインスタンスで指定されたソート順序に従って、最初に一致するドキュメントを削除します。
delete_one()
メソッドは DeleteResult タイプを返します。このタイプには、削除されたドキュメントの合計数など、 削除操作の結果に関する情報が含まれます。
削除操作の詳細については、 ドキュメントの削除のガイドを参照してください。
例
この例では、 sample_restaurants
データベース内のrestaurants
コレクションからクエリフィルターに一致するドキュメントを削除します。 delete_one()
メソッドは、name
フィールドの値が "Haagen-Dazs"
であり、かつ borough
フィールドの値が "Brooklyn"
である最初のドキュメントを削除します。
restaurants
コレクション内のドキュメントには、Document
型またはカスタムデータ型のインスタンスとしてアクセスできます。 コレクションのデータを表すデータ型を指定するには、強調表示された行の <T>
型パラメータを次のいずれかの値に置き換えます。
<Document>
:コレクションドキュメントはBSONドキュメントとしてアクセスします<Restaurant>
: コードの上部で定義されたRestaurant
構造体のインスタンスとしてコレクションドキュメントにアクセスします
AsynchronousSynchronous各実行時に対応するコードを表示するには、 タブまたは タブを選択します。
use mongodb::{ bson::{ Document, doc }, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, borough: String, } 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! { "name": "Haagen-Dazs" }, doc! { "borough": "Brooklyn" } ] }; let result = my_coll.delete_one(filter).await?; println!("Deleted documents: {}", result.deleted_count); Ok(()) }
Deleted documents: 1
use mongodb::{ bson::{ Document, doc }, sync::{ Client, Collection } }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, borough: String, } 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! { "name": "Haagen-Dazs" }, doc! { "borough": "Brooklyn" } ] }; let result = my_coll.delete_one(filter).run()?; println!("Deleted documents: {}", result.deleted_count); Ok(()) }
Deleted documents: 1