Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Rust 드라이버
/

문서 교체하기

인스턴스 에서replace_one() 메서드를 호출하여 컬렉션 의 문서 바꿀 수 있습니다.Collection

다음 매개변수를 replace_one() 메서드에 전달합니다:

  • 일치시킬 기준을 지정하는 쿼리 필터

  • 첫 번째 일치 문서를 대체할 필드와 값이 포함된 대체 문서

replace_one() 메서드는 수정된 문서 수와 같은 바꾸기 작업 결과에 대한 정보가 포함된 UpdateResult 유형을 반환합니다.

replace_one() 메서드에 학습 보려면 문서 수정 가이드 의 문서 교체 섹션을 참조하세요.

이 예는 sample_restaurants 데이터베이스의 restaurants collection에 있는 문서를 대체합니다. 이 예제에서는 name, boroughcuisine 필드가 있는 Restaurant 구조체를 사용하여 collection의 문서를 모델링합니다.

다음 코드는 name 필드의 값이 "Landmark Coffee Shop" 인 문서를 새 문서로 대체하는 코드입니다. MongoDB는 쿼리 필터와 일치하는 첫 번째 문서를 대체합니다.

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?;
let my_coll: Collection<Restaurant> = client
.database("sample_restaurants")
.collection("restaurants");
let filter = doc! { "name": "Landmark Coffee Shop" };
let replacement = Restaurant {
borough: "Brooklyn".to_string(),
cuisine: "Café/Coffee/Tea".to_string(),
name: "Harvest Moon Café".to_string(),
};
let res = my_coll.replace_one(filter, replacement, None).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)?;
let my_coll: Collection<Restaurant> = client
.database("sample_restaurants")
.collection("restaurants");
let filter = doc! { "name": "Landmark Coffee Shop" };
let replacement = Restaurant {
borough: "Brooklyn".to_string(),
cuisine: "Café/Coffee/Tea".to_string(),
name: "Harvest Moon Café".to_string(),
};
let res = my_coll.replace_one(filter, replacement, None)?;
println!("Replaced documents: {}", res.modified_count);
Ok(())
}
Replaced documents: 1

돌아가기

다중 업데이트