AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

문서 삭제

이 가이드에서는 삭제 작업 을 사용하여 MongoDB collection에서 문서를 제거하는 방법에 대해 설명합니다.

이 가이드에는 다음 섹션이 포함되어 있습니다.

  • 예제용 샘플 데이터는 삭제 작업 예제에서 사용되는 샘플 데이터를 나타냅니다.

  • 삭제 작업 에서는 드라이버를 사용하여 삭제 작업을 실행하는 방법을 설명합니다.

  • 삭제 예제에서는 삭제 작업에 대한 코드 예제를 제공합니다.

  • 추가 정보에서 이 가이드에 언급된 유형 및 메소드에 대한 리소스 및 API 문서 링크를 찾을 수 있습니다.

이 가이드의 예에서는 다음 샘플 문서를 사용합니다. 각 문서는 매장 재고에 있는 품목을 나타내며 분류 및 단가에 대한 정보를 포함합니다.

{ "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 에서 사용할 수 있는 옵션에 대해 설명합니다.

옵션
설명

collation

결과를 정렬할 때 사용할 데이터 정렬입니다. 데이터 정렬에 대해 자세히 학습 데이터 정렬 가이드 참조하세요.

유형: Collation
기본값: None

write_concern

작업에 대한 쓰기 고려 (write concern) . 이 옵션을 설정하다 하지 않으면 작업은 컬렉션 에 대해 설정하다 쓰기 고려 (write concern) 상속합니다. 쓰기 (write) 고려에 대해 자세히 학습 서버 매뉴얼에서 쓰기 고려를 참조하세요.

유형: WriteConcern

hint

작업에 사용할 인덱스 입니다. 인덱스에 대해 자세히 학습 서버 매뉴얼의 인덱스를 참조하세요. 이 옵션은 MongoDB Server 버전 이상에 연결할 때만 사용할 수 4.4 있습니다.

유형: Hint
기본값: None

let_vars

매개변수와 값의 맵입니다. 이러한 매개변수는 집계 표현식에서 변수로 액세스할 수 있습니다. 이 옵션은 MongoDB Server 버전 5.0 이상에 연결할 때에만 사용할 수 있습니다.

유형: Document

comment

Bson 데이터베이스 프로파일러, 및 로그를 통해 추적하는 작업에 연결된 임의의currentOp 값입니다. 이 옵션은 MongoDB Server 버전 이상에 연결할 때만 사용할 수 4.4 있습니다.

유형: Bson
기본값: 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 };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
borough: String,
}
#[tokio::main]
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 };
#[derive(Serialize, Deserialize, Debug)]
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 };
#[derive(Debug, Serialize, Deserialize)]
struct Address {
street: String,
city: String,
}
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
name: String,
borough: String,
address: Address,
}
#[tokio::main]
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 };
#[derive(Debug, Serialize, Deserialize)]
struct Address {
street: String,
city: String,
}
#[derive(Serialize, Deserialize, Debug)]
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 문서를 참조하세요.