Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /

문서 교체

이 가이드 에서는 replace_one() 메서드를 통해 Rust 운전자 사용하여 MongoDB 컬렉션 의 문서를 바꾸는 방법을 학습 수 있습니다.

바꾸기 작업은 _id 필드를 제외한 문서의 모든 기존 필드를 제거하고 제거된 필드를 새 필드 및 값으로 대체합니다.

참고

문서의 특정 필드를 업데이트 방법을 학습 보려면 문서 업데이트 가이드 참조하세요.

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

  • 문서 교체 에서는 운전자 를 사용하여 교체 작업을 실행하는 방법을 설명합니다.

  • 바꾸기 동작 수정에서는 메서드의 기본값 동작을 수정하는 방법을 설명합니다.replace_one()

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

MongoDB 컬렉션 의 각 문서 에는 고유하고 변경할 수 없는 _id 필드 있습니다. 대체 작업을 통해 _id 필드 변경하려고 하면 운전자 WriteError 를 발생시키고 업데이트를 수행하지 않습니다.

replace_one() 메서드를 사용하여 바꾸기 작업을 수행할 수 있습니다. 이 메서드는 _id 필드 제외한 문서 의 모든 기존 필드를 제거하고 제거된 필드를 지정한 새 필드 및 값으로 대체합니다.

옵션 빌더 메서드를 메서드에 연결할 수도 replace_one() 있습니다. 이 메서드의 동작 수정에 대해 학습 이 가이드 의 Modify Replace Behavior(교체 동작 수정) 섹션을 참조하세요.

복합 작업을 사용하여 한 번의 조치로 데이터를 검색하고 수정할 수 있습니다. 자세한 내용은 복합 연산 가이드를 참조하세요.

replace_one() 메서드는 다음 매개 변수를 사용합니다.

  • 대체할 문서 와 일치하는쿼리 필터하다

  • 기존 문서 대체할 필드와 값이 포함된 대체 문서

대체 문서는 다음과 같은 형식을 사용합니다.

doc! { "<field>": <value>, "<field>": <value>, ... }

작업이 성공하면 replace_one() 메서드는 UpdateResult 유형을 반환합니다. UpdateResult 유형에는 작업을 설명하는 다음 속성이 포함되어 있습니다.

속성
설명

matched_count

필터하다 와 일치하는 문서 수

modified_count

작업으로 수정된 문서 수입니다.

upserted_id

업서트된 문서의 _id(없는 경우 비어 있음)

replace_one() 에 전달한 쿼리 필터와 일치하는 문서가 여러 개 있는 경우 메서드는 첫 번째로 일치하는 문서를 선택하고 대체합니다. 쿼리 필터와 일치하는 문서가 없는 경우 교체 작업은 변경되지 않습니다.

이 섹션에서는 replace_one() 메서드를 사용하여 컬렉션 의 문서를 바꾸는 방법을 보여주는 예를 제공합니다.

다음 문서는 회사 직원에 대해 설명합니다.

{
"_id": ObjectId('4501'),
"name": "Matt DeGuy",
"role": "Consultant",
"team_members": [ "Jill Gillison", "Susan Lee" ]
}

이 예에서는 replace_one() 메서드를 사용하여 앞의 문서를 다음 필드가 있는 문서로 바꿉니다.

  • "Susan Lee"name

  • "Lead Consultant"role

  • [ "Jill Gillison" ]team_members

let replace_doc = doc! {
"name": "Susan Lee",
"role": "Lead Consultant",
"team_members": vec! [ "Jill Gillison" ]
};
let res = my_coll
.replace_one(doc! { "name": "Matt DeGuy" }, replace_doc)
.await?;
println!(
"Matched documents: {}\nModified documents: {}",
res.matched_count, res.modified_count
);
Matched documents: 1
Modified documents: 1

대체된 문서에는 대체 문서의 내용과 변경할 수 없는 _id 필드가 포함되어 있습니다.

{
"_id": ObjectId('4501'),
"name": "Susan Lee",
"role": "Lead Consultant",
"team_members": [ "Jill Gillison" ]
}

이 예시 sample_restaurants 데이터베이스 의 restaurants 컬렉션 에 있는 문서 대체합니다. replace_one() 메서드는 name 필드 의 값이 "Landmark Coffee Shop" 인 첫 번째 문서 새 문서 로 대체합니다.

restaurants 컬렉션 의 문서에 Document 유형 또는 사용자 지정 데이터 유형 의 인스턴스로 액세스 할 수 있습니다. 컬렉션의 데이터를 나타내는 데이터 유형 지정하려면 강조 표시된 줄에서 다음 작업을 수행합니다.

  • 컬렉션 문서에 BSON 문서로 액세스 하려면 <T> 유형 매개변수를 <Document> 로 바꾸고 <struct or doc> 자리 표시자를 replace_doc로 바꿉니다.

  • Restaurant 구조체의 인스턴스로 컬렉션 문서에 액세스 하려면 <T> 유형 매개 변수를 <Restaurant> 로 바꾸고 <struct or doc> 자리 표시자를 replace_struct로 바꿉니다. Restaurant 구조체는 코드 파일 상단에 정의되어 있습니다.

Asynchronous 또는 Synchronous 탭을 선택하여 각 런타임에 해당하는 코드를 확인합니다.

use std::env;
use mongodb::{ bson::doc, Client, Collection };
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
borough: String,
cuisine: String,
name: 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! { "name": "Landmark Coffee Shop" };
let replace_doc = doc! {
"borough": "Brooklyn",
"cuisine": "Café/Coffee/Tea",
"name": "Harvest Moon Café",
};
let replace_struct = Restaurant {
borough: "Brooklyn".to_string(),
cuisine: "Café/Coffee/Tea".to_string(),
name: "Harvest Moon Café".to_string(),
};
// Replace <struct or doc> with the replace_struct or replace_doc variable
let res = my_coll.replace_one(filter, <struct or doc>).await?;
println!("Replaced documents: {}", res.modified_count);
Ok(())
}
Replaced documents: 1
use std::env;
use mongodb::{ bson::doc, sync::{ Client, Collection } };
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
borough: String,
cuisine: String,
name: 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! { "name": "Landmark Coffee Shop" };
let replace_doc = doc! {
"borough": "Brooklyn",
"cuisine": "Café/Coffee/Tea",
"name": "Harvest Moon Café",
};
let replace_struct = Restaurant {
borough: "Brooklyn".to_string(),
cuisine: "Café/Coffee/Tea".to_string(),
name: "Harvest Moon Café".to_string(),
};
// Replace <struct or doc> with the replace_struct or replace_doc variable
let res = my_coll.replace_one(filter, <struct or doc>).run()?;
println!("Replaced documents: {}", res.modified_count);
Ok(())
}
Replaced documents: 1

ReplaceOptions 구조체 필드를 설정하다 옵션 메서드를 호출하여 replace_one() 메서드의 동작을 수정할 수 있습니다.

참고

설정 옵션

옵션 빌더 메서드를 replace_one() 메서드 호출에 직접 연결하여 ReplaceOptions 필드를 설정하다 수 있습니다. 이전 버전의 운전자 를 사용하는 경우 옵션 빌더 메서드를 builder() 메서드에 연결하여 ReplaceOptions 인스턴스 를 구성해야 합니다. 그런 다음 옵션 인스턴스 를 replace_one() 에 매개 변수로 전달합니다.

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

옵션
설명

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 the guide on Schema Validation.

Type: bool
Default: false

upsert

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

Type: bool

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.

Type: Hint
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 MongoDB Server manual.

Type: WriteConcern

let_vars

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

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

다음 코드는 upsert() 메서드를 replace_one() 메서드에 연결하여 upsert 필드 를 설정하다 하는 방법을 보여줍니다.

let res = my_coll
.replace_one(filter_doc, replace_doc)
.upsert(true)
.await?;

이 가이드의 개념에 대한 자세한 내용은 다음 문서를 참조하세요.

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

돌아가기

문서 업데이트

이 페이지의 내용