Docs Menu
Docs Home
/ / /
C#/.NET
/

문서 교체하기

이 페이지의 내용

  • 예제
  • 예상 결과
  • 추가 정보
  • API 문서

컬렉션 객체의 ReplaceOne() 동기 메서드 또는 ReplaceOneAsync() 비동기 메서드를 사용하여 한 문서를 다른 문서로 바꿀 수 있습니다.

다음 코드는 cuisine 필드에 "Pizza" 값이 있는 restaurants 컬렉션의 첫 번째 문서를 대체합니다. 교체 후 이 문서에는 값이 "Mongo's Pizza"인 name 필드가 있고 addressborough 필드에 대한 새 값이 있습니다.

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

// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza"
var filter = Builders<Restaurant>.Filter
.Eq(r => r.Cuisine, "Pizza");
// Finds the ID of the first restaurant document that matches the filter
var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First();
var oldId = oldPizzaRestaurant.Id;
// Generates a new restaurant document
Restaurant newPizzaRestaurant = new()
{
Id = oldId,
Name = "Mongo's Pizza",
Cuisine = "Pizza",
Address = new()
{
Street = "Pizza St",
ZipCode = "10003"
},
Borough = "Manhattan",
};
// Asynchronously replaces the existing restaurant document with the new document
return await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant);

ReplaceOneAsync() 작업의 완전히 실행 가능한 예제는 ReplaceOneAsync 코드 샘플을 참조하세요.

// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza"
var filter = Builders<Restaurant>.Filter
.Eq(r => r.Cuisine, "Pizza");
// Finds the ID of the first restaurant document that matches the filter
var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First();
var oldId = oldPizzaRestaurant.Id;
// Generates a new restaurant document
Restaurant newPizzaRestaurant = new()
{
Id = oldId,
Name = "Mongo's Pizza",
Cuisine = "Pizza",
Address = new()
{
Street = "Pizza St",
ZipCode = "10003"
},
Borough = "Manhattan",
};
// Replaces the existing restaurant document with the new document
return _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant);

작업의 완전히 실행 가능한 예제는 ReplaceOne ReplaceOne() 코드 샘플을 참조하세요.

앞의 전체 예제 중 하나를 실행하면 다음과 같은 결과가 나옵니다.

First pizza restaurant before replacement: J&V Famous Pizza
Restaurants modified by replacement: 1
First pizza restaurant after replacement: Mongo's Pizza
Resetting sample data...done.

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

빌더 사용에 대해 자세히 알아보려면 빌더를 사용한 작업을 참조하세요.

돌아가기

다수 문서 업데이트