Docs Menu
Docs Home
/ /

복합 작업

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

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

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

  • 문서 한 개 찾기 및 삭제

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

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

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

  • 예제용 샘플 데이터는 복합 작업 예제에서 사용되는 샘플 데이터를 제공합니다.

  • 문서 찾기 및 삭제 에서는 한 번의 작업으로 문서를 찾고 삭제하는 방법을 설명합니다.

  • 문서 찾기 및 업데이트 에서는 한 번의 작업으로 문서를 찾고 업데이트하는 방법을 설명합니다.

  • 문서 찾기 및 바꾸기 에서는 한 번의 작업으로 문서를 찾고 바꾸는 방법을 설명합니다.

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

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

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

{ "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

The maximum amount of time in milliseconds that the query can run.

Type: Duration

projection

The projection to use when returning results.

Type: Document
Default: 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

The collation to use when sorting results. To learn more about collations, see the Collations guide.

Type: Collation
Default: 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

A map of parameters and values. You can access these parameters as variables in aggregation expressions. This option is available only when connecting to MongoDB Server versions 5.0 and later.

Type: Document

comment

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: Bson
Default: 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);
Deleted document:
Some(Document({"_id": ObjectId("..."),
"name": String("Deanna Porowski"), "age": Int32(10), "school":
String("Lakeside Elementary")}))

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

참고

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

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

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

옵션
설명

array_filters

The set of filters specifying the array elements to which the update applies.

Type: 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

The maximum amount of time in milliseconds that the query can run.

Type: Duration

projection

The projection to use when returning results.

Type: Document
Default: None

return_document

If Before, the operation returns the document before the update. If After, the operation returns the updated document.

Type: ReturnDocument
Default: 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

If true, the operation inserts a document if no documents match the query filter.

Type: bool
Default: 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

The collation to use when sorting results. To learn more about collations, see the Collations guide.

Type: Collation
Default: 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

A map of parameters and values. You can access these parameters as variables in aggregation expressions. This option is available only when connecting to MongoDB Server versions 5.0 and later.

Type: Document

comment

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: Bson
Default: 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);
Updated document:
Some(Document({"_id": ObjectId("..."),
"name": String("Ben Joseph"), "age": Int32(17), "school":
String("Durango High School")}))

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

The maximum amount of time in milliseconds that the query can run.

Type: Duration

projection

The projection to use when returning results.

Type: Document
Default: None

return_document

If Before, the operation returns the document before the update. If After, the operation returns the updated document.

Type: ReturnDocument
Default: 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

If true, the operation inserts a document if no documents match the query filter.

Type: bool
Default: 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

The collation to use when sorting results. To learn more about collations, see the Collations guide.

Type: Collation
Default: 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

A map of parameters and values. You can access these parameters as variables in aggregation expressions. This option is available only when connecting to MongoDB Server versions 5.0 and later.

Type: Document

comment

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: Bson
Default: 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"문자열이 포함된 문서와 일치하는 쿼리 필터

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

  • 교체 후 문서를 반환하고 출력에서 nameschool 필드만 프로젝트하는 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);
Document after replacement:
Some(Document({"name": String("Toby Fletcher"), "school":
String("Durango High School")}))

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

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

돌아가기

대량 작업

이 페이지의 내용