문서 삭제
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
구조체의 인스턴스로 컬렉션 문서에 액세스합니다.
Asynchronous 또는 Synchronous 탭을 선택하여 각 런타임에 해당하는 코드를 확인합니다.
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