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

복합 작업

이 가이드에서는 Rust 드라이버를 사용하여 복합 연산 을 수행하는 방법을 배울 수 있습니다.

복합 작업은 읽기 및 쓰기 (write) 작업의 기능을 하나의 원자성 조치 으로 결합합니다. 읽기 작업과 쓰기 (write) 작업을 순서대로 수행하면 작업 사이에 누군가가 대상 문서 를 변경하여 예기치 않은 결과가 발생할 수 있습니다. 복합 작업을 수행할 때 MongoDB 는 작업이 완료될 때까지 수정 중인 문서 에 쓰기 락 (write lock) 을 설정하여 중간 데이터 변경을 방지합니다.

드라이버를 사용하여 다음과 같은 복합 작업을 수행할 수 있습니다.

  • 문서 한 개 찾기 및 삭제

  • 하나의 문서 찾기 및 업데이트

  • 하나의 문서 찾기 및 바꾸기

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

팁

한 번에 두 개 이상의 문서에서 원자성 읽기 및 쓰기 작업을 수행하는 방법을 알아보려면 트랜잭션 가이드를 참조하세요.

이 가이드의 예에서는 다음 샘플 문서를 사용합니다. 각 문서는 학생을 나타내며 해당 문서의 연령 및 재학 중인 학교에 대한 정보를 포함합니다.

{ "name": "Alex Johnson", "age": 8, "school": "Lakeside Elementary" },
{ "name": "Samara Khan", "age": 11, "school": "Rolling Hills Middle School" },
{ "name": "Ben Joseph", "age": 16, "school": "Aurora High School" },
{ "name": "Deanna Porowski", "age": 10, "school": "Lakeside Elementary" }

find_one_and_delete() 메서드는 지정된 쿼리 필터와 일치하는 첫 번째 문서를 찾아 삭제합니다. 문서가 필터 기준과 일치하는 경우 메서드는 Some 유형을 반환합니다. 일치하는 문서가 없으면 None 유형을 반환합니다.

참고

문서 찾기와 삭제 사이에 다른 작업을 수행하려면 find_one() 메서드를 호출한 다음 delete_one() 메서드를 호출하면 됩니다.

선택적으로 FineOneAndDeleteOptions 인스턴스를 매개변수로 전달하여 find_one_and_delete() 메서드의 동작을 수정할 수 있습니다. 각 설정에 기본값을 사용하려면 옵션 매개변수에 None 값을 지정합니다.

다음 표에서는 FineOneAndDeleteOptions 에서 사용할 수 있는 옵션에 대해 설명합니다.

옵션
설명

max_time

쿼리가 실행될 수 있는 최대 시간(밀리초)입니다.

유형: Duration

projection

결과를 반환할 때 사용할 프로젝션입니다.

유형: Document
기본값: None

sort

The sorting order to use when returning results. By default, the driver returns documents in their natural order, or as they appear in the database. To learn more, see natural order in the Server manual glossary.

Type: Document
Default: None

write_concern

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

collation

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

유형: Collation
기본값: None

hint

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: Hint
Default: None

let_vars

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

유형: Document

comment

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

유형: Bson
기본값: None

Rust 드라이버는 FindOneAndDeleteOptions 인스턴스 생성을 위한 빌더 디자인 패턴을 구현합니다. 유형의 builder() 메서드를 사용하면 옵션 빌더 함수를 한 번에 하나씩 연결하여 옵션 인스턴스를 구성할 수 있습니다.

다음 코드는 FindOneAndDeleteOptions 인스턴스를 구성하고 이를 find_one_and_delete() 메서드에 전달하는 방법을 보여줍니다.

let opts = FindOneAndDeleteOptions::builder().comment(bson!("hello")).build();
let res = my_coll.find_one_and_delete(filter, opts).await?;

다음 예에서는 find_one_and_delete() 메서드를 사용하여 age 필드의 값이 10 보다 작거나 같은 첫 번째 문서를 일치시키고 삭제합니다.

let filter = doc! { "age": doc! { "$lte": 10 } };
let res = my_coll.find_one_and_delete(filter, None).await?;
println!("Deleted document:\n{:?}", res);

find_one_and_update() 메서드는 지정된 쿼리 필터와 일치하는 첫 번째 문서를 찾아 업데이트합니다. 이 작업은 업데이트 문서에 제공한 사양을 기반으로 문서를 업데이트합니다. 문서가 필터 기준과 일치하는 경우 메서드는 Some 유형을 반환합니다. 일치하는 문서가 없으면 None 유형을 반환합니다.

참고

문서 찾기와 업데이트 사이에 다른 작업을 수행하려면 find_one() 메서드를 호출한 다음 update_one() 메서드를 호출하면 됩니다.

선택적으로 FindOneAndUpdateOptions 인스턴스를 매개변수로 전달하여 find_one_and_update() 메서드의 동작을 수정할 수 있습니다. 각 설정에 기본값을 사용하려면 옵션 매개변수에 None 값을 지정합니다.

다음 표에서는 FineOneAndDeleteOptions 에서 사용할 수 있는 옵션에 대해 설명합니다.

옵션
설명

array_filters

업데이트가 적용되는 배열 요소를 지정하는 필터 설정입니다.

유형: Vec<Document>

bypass_document_validation

If true, allows the driver to perform a write that violates document-level validation. To learn more about validation, see Schema Validation in the Server manual.

Type: bool
Default: false

max_time

쿼리가 실행될 수 있는 최대 시간(밀리초)입니다.

유형: Duration

projection

결과를 반환할 때 사용할 프로젝션입니다.

유형: Document
기본값: None

return_document

Before인 경우 이 작업은 업데이트 전의 문서를 반환합니다. After인 경우 이 작업은 업데이트된 문서를 반환합니다.

유형: ReturnDocument
기본값: ReturnDocument::Before

sort

The sorting order to use when returning results. By default, the driver returns documents in their natural order, or as they appear in the database. To learn more, see natural order in the Server manual glossary.

Type: Document
Default: None

upsert

참인 경우, 쿼리 필터와 일치하는 문서가 없는 경우 작업이 문서를 삽입합니다.

유형: bool
기본값: false

write_concern

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

collation

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

유형: Collation
기본값: None

hint

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: Hint
Default: None

let_vars

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

유형: Document

comment

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

유형: Bson
기본값: None

Rust 드라이버는 FindOneAndUpdateOptions 인스턴스 생성을 위한 빌더 디자인 패턴을 구현합니다. 유형의 builder() 메서드를 사용하면 옵션 빌더 메서드를 한 번에 하나씩 연결하여 옵션 인스턴스를 구성할 수 있습니다.

다음 코드는 FindOneAndUpdateOptions 인스턴스를 구성하고 이를 find_one_and_update() 메서드에 전달하는 방법을 보여줍니다.

let opts = FindOneAndUpdateOptions::builder().comment(bson!("hello")).build();
let res = my_coll.find_one_and_update(filter, update, opts).await?;

이 예에서는 다음 매개 변수를 사용하여 find_one_and_update() 메서드를 호출하는 방법을 보여 줍니다.

  • school 값이 "Aurora High School"인 문서와 일치하는 쿼리 필터

  • school 필드를 "Durango High School" (으)로 설정하고 age 필드를 1만큼 증가시키는 업데이트 문서입니다.

  • 업데이트 후 문서를 반환하는 FindOneAndUpdateOptions 인스턴스

let filter = doc! { "school": "Aurora High School" };
let update =
doc! { "$set": doc! { "school": "Durango High School" },
"$inc": doc! { "age": 1 } };
let opts = FindOneAndUpdateOptions::builder()
.return_document(Some(ReturnDocument::After))
.build();
let res = my_coll.find_one_and_update(filter, update, opts).await?;
println!("Updated document:\n{:?}", res);

find_one_and_replace() 메서드는 지정된 쿼리 필터와 일치하는 첫 번째 문서를 찾아서 바꿉니다. 이 작업은 _id 필드를 제외한 문서의 모든 필드를 사용자가 제공한 필드 및 값으로 대체합니다. 문서가 필터 기준과 일치하면 메서드는 Some 유형을 반환합니다. 일치하는 문서가 없으면 None 유형을 반환합니다.

참고

문서 찾기와 바꾸기 사이에 다른 작업을 수행하려면 find_one() 메서드를 호출한 다음 replace_one() 메서드를 호출하면 됩니다.

선택적으로 FindOneAndReplaceOptions 인스턴스를 매개변수로 전달하여 find_one_and_replace() 메서드의 동작을 수정할 수 있습니다. 각 설정에 기본값을 사용하려면 옵션 매개변수에 None 값을 지정합니다.

다음 표에서는 FindOneAndReplaceOptions 에서 사용할 수 있는 옵션에 대해 설명합니다.

옵션
설명

bypass_document_validation

If true, allows the driver to perform a write that violates document-level validation. To learn more about validation, see Schema Validation in the Server manual.

Type: bool
Default: false

max_time

쿼리가 실행될 수 있는 최대 시간(밀리초)입니다.

유형: Duration

projection

결과를 반환할 때 사용할 프로젝션입니다.

유형: Document
기본값: None

return_document

Before인 경우 이 작업은 업데이트 전의 문서를 반환합니다. After인 경우 이 작업은 업데이트된 문서를 반환합니다.

유형: ReturnDocument
기본값: ReturnDocument::Before

sort

The sorting order to use when returning results. By default, the driver returns documents in their natural order, or as they appear in the database. To learn more, see natural order in the Server manual glossary.

Type: Document
Default: None

upsert

참인 경우, 쿼리 필터와 일치하는 문서가 없는 경우 작업이 문서를 삽입합니다.

유형: bool
기본값: false

write_concern

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

collation

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

유형: Collation
기본값: None

hint

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: Hint
Default: None

let_vars

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

유형: Document

comment

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

유형: Bson
기본값: None

Rust 드라이버는 FindOneAndReplaceOptions 인스턴스 생성을 위한 빌더 디자인 패턴을 구현합니다. 유형의 builder() 메서드를 사용하면 옵션 빌더 함수를 한 번에 하나씩 연결하여 옵션 인스턴스를 구성할 수 있습니다.

다음 코드는 FindOneAndReplaceOptions 인스턴스를 구성하고 이를 find_one_and_replace() 메서드에 전달하는 방법을 보여줍니다.

let opts = FindOneAndReplaceOptions::builder().comment(bson!("hello")).build();
let res = my_coll.find_one_and_replace(filter, replacement, opts).await?;

이 예에서는 다음 매개 변수를 사용하여 find_one_and_replace() 메서드를 호출하는 방법을 보여 줍니다.

  • name 값에 "Johnson"문자열이 포함된 문서와 일치하는 쿼리 필터

  • 신규 학생에 대해 설명하는 대체 문서

  • 교체 후 문서를 반환하고 출력에서 name 및 school 필드만 프로젝트하는 FindOneAndReplaceOptions 인스턴스

let filter = doc! { "name": doc! { "$regex": "Johnson" } };
let replacement =
doc! { "name": "Toby Fletcher",
"age": 14,
"school": "Durango High School" };
let opts = FindOneAndReplaceOptions::builder()
.return_document(Some(ReturnDocument::After))
.projection(doc! { "name": 1, "school": 1, "_id": 0 })
.build();
let res = my_coll.find_one_and_replace(filter, replacement, opts).await?;
println!("Document after replacement:\n{:?}", res);

이 가이드의 작업에 대해 자세히 알아보려면 다음 문서를 참조하세요.

이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.