개요
이 가이드에서는 삭제 작업 을 사용하여 MongoDB collection에서 문서를 제거하는 방법에 대해 설명합니다.
이 가이드에는 다음 섹션이 포함되어 있습니다.
예시용 샘플 데이터
이 가이드의 예에서는 다음 샘플 문서를 사용합니다. 각 문서는 매장 재고에 있는 품목을 나타내며 분류 및 단가에 대한 정보를 포함합니다.
{ "item": "trowel", "category": "garden", "unit_price": 9.89 }, { "item": "placemat", "category": "kitchen", "unit_price": 3.19 }, { "item": "watering can", "category": "garden", "unit_price": 11.99 }
삭제 작업
Rust 드라이버는 삭제 작업을 수행하기 위해 delete_one() 및 delete_many() 메서드를 제공합니다.
매개변수
delete_one() 및 delete_many() 메서드는 쿼리 필터를 매개 변수로 사용합니다. 쿼리 필터는 문서가 일치시킬 기준을 형성하는 필드와 값으로 구성됩니다.
옵션
옵션 빌더 메서드를 delete_one() 및 delete_many() 에 연결하여 삭제 작업 메서드의 동작을 수정할 수 있습니다. 이러한 옵션 메서드 설정하다 DeleteOptions 구조체 필드를 설정합니다.
참고
설정 옵션
옵션 빌더 메서드를 삭제 메서드 호출에 직접 연결하여 DeleteOptions 필드를 설정하다 수 있습니다. 이전 버전의 운전자 를 사용하는 경우 옵션 빌더 메서드를 builder() 메서드에 연결하여 DeleteOptions 인스턴스 를 구성해야 합니다. 그런 다음 옵션 인스턴스 를 delete_one() 또는 delete_many() 에 매개 변수로 전달합니다.
다음 표에서는 DeleteOptions 에서 사용할 수 있는 옵션에 대해 설명합니다.
옵션 | 설명 |
|---|---|
| The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: CollationDefault: None |
| The write concern for the operation. If you don't set this
option, the operation inherits the write concern set for
the collection. To learn more about write concerns, see
Write Concern in the
Server manual. Type: WriteConcern |
| The index to use for the operation. To learn more about
indexes, see Indexes in the Server
manual. This option is available only when connecting to
MongoDB Server versions 4.4 and later. Type: HintDefault: None |
| A map of parameters and values. These parameters can be accessed
as variables in aggregation expressions. This option is available
only when connecting to MongoDB Server versions 5.0 and later. Type: Document |
| An arbitrary Bson value tied to the operation to trace
it through the database profiler, currentOp, and
logs. This option is available only when connecting to
MongoDB Server versions 4.4 and later.Type: BsonDefault: None |
다음 코드는 comment() 메서드를 delete_one() 메서드에 연결하여 comment 필드 를 설정하다 하는 방법을 보여줍니다.
let res = my_coll .delete_one(filter) .comment(bson!("hello!")) .await?;
반환 값
delete_one() 및 delete_many() 메서드는 DeleteResult 유형을 반환합니다. 이 유형에는 삭제된 문서 수를 설명하는 deleted_count 속성이 포함되어 있습니다. 지정한 쿼리 필터와 일치하는 문서가 없는 경우 삭제 작업은 어떤 문서도 제거하지 않으며 deleted_count 의 값은 0 입니다.
예시 삭제
이 섹션에서는 다음 삭제 작업에 대한 코드 예제를 제공합니다.
하나의 예시 삭제
다음 예시 delete_one() 메서드를 사용하여 item 값이 "placemat"인 문서 삭제 .
let filter = doc! { "item": "placemat" }; let res = my_coll.delete_one(filter).await?; println!("Deleted documents: {}", res.deleted_count);
Deleted documents: 1
전체 파일 예시: 문서 삭제
이 예시 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
다수 삭제 예시
이 예에서는 다음 조치를 수행합니다.
delete_many()메서드 호출category값이"garden"인 문서와 일치하는 쿼리 필터하다 를delete_many()에 전달합니다.hint()메서드를delete_many()에 연결하여_id_인덱스 를 삭제 작업에 대한 힌트로 사용합니다.
let filter = doc! { "category": "garden" }; let hint = Hint::Name("_id_".to_string()); let res = my_coll .delete_many(filter) .hint(hint) .await?; println!("Deleted documents: {}", res.deleted_count);
Deleted documents: 2
참고
앞의 코드 예시에서 delete_many() 대신 delete_one() 메서드를 사용하는 경우 드라이버는 쿼리 필터와 일치하는 두 문서 중 첫 번째 문서만 삭제합니다.
전체 파일 예시: 여러 문서 삭제
이 예시 sample_restaurants 데이터베이스 의 restaurants 컬렉션 에서 쿼리 필터하다 와 일치하는 모든 문서를 삭제합니다. delete_many() 메서드는 borough 필드 의 값이 "Manhattan" 이고 address.street 필드 의 값이 "Broadway"인 문서를 삭제합니다.
restaurants 컬렉션 의 문서에 Document 유형 또는 사용자 지정 데이터 유형 의 인스턴스로 액세스 할 수 있습니다. 컬렉션의 데이터를 나타내는 데이터 유형 지정하려면 강조 표시된 줄의 <T> 유형 매개변수를 다음 값 중 하나로 바꿉니다.
<Document>: 컬렉션 문서를 BSON 문서로 액세스합니다.<Restaurant>: 코드 상단에 정의된Restaurant구조체의 인스턴스로 컬렉션 문서에 액세스합니다.
Asynchronous 또는 Synchronous 탭을 선택하여 각 런타임에 해당하는 코드를 확인합니다.
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
추가 정보
이 가이드의 작업에 대해 자세히 알아보려면 다음 문서를 참조하세요.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.