Collection 인스턴스 에서 delete_many() 메서드를 호출하여 한 번의 작업으로 컬렉션 에서 여러 문서를 삭제 수 있습니다.
쿼리 필터를 delete_many() 메서드에 전달하여 collection에서 필터와 일치하는 문서를 삭제합니다. 필터를 포함하지 않으면 MongoDB는 collection의 모든 문서를 삭제합니다.
delete_many() 메서드는 DeleteResult 유형을 반환합니다. 이 유형에는 삭제된 총 문서 수와 같은 삭제 작업에 대한 정보가 포함됩니다.
삭제 작업에 학습 보려면 문서 삭제 가이드 를 참조하세요.
팁
collection의 모든 문서를 삭제하려면 인스턴스에서 메서드를 호출하는 drop() 것이 Collection 좋습니다. drop() 메서드에 대해 자세히 알아보려면 데이터베이스 및 collection 가이드 의 collection 삭제 섹션을 참조하세요.
예시
이 예시에서는 sample_restaurants 데이터베이스의 restaurants 컬렉션에서 쿼리 필터와 일치하는 모든 문서를 삭제합니다.
이 예에서는 쿼리 필터를 delete_many() 메서드에 매개변수로 전달합니다. 필터는 borough 필드의 값이 "Manhattan" 이고 address.street 필드의 값이 "Broadway" 인 문서와 일치합니다.
Asynchronous 또는 Synchronous 탭을 선택하여 각 런타임에 해당하는 코드를 확인합니다.
use mongodb::{ bson::{ Document, doc }, Client, Collection }; async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; let my_coll: Collection<Document> = client .database("sample_restaurants") .collection("restaurants"); let filter = doc! { "$and": [ doc! { "borough": "Manhattan" }, doc! { "address.street": "Broadway" } ] }; let result = my_coll.delete_many(filter, None).await?; println!("Deleted documents: {}", result.deleted_count); Ok(()) }
// Your values might differ Deleted documents: 615
use mongodb::{ bson::{ Document, doc }, sync::{ Client, Collection } }; fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; let my_coll: Collection<Document> = client .database("sample_restaurants") .collection("restaurants"); let filter = doc! { "$and": [ doc! { "borough": "Manhattan" }, doc! { "address.street": "Broadway" } ] }; let result = my_coll.delete_many(filter, None)?; println!("Deleted documents: {}", result.deleted_count); Ok(()) }
// Your values might differ Deleted documents: 615