ドキュメントの削除
コレクションからドキュメントを削除するには、 インスタンスで 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