collection 객체에서 ReplaceOne() 동기 방법 또는 ReplaceOneAsync() 비동기 방법을 사용하여 한 문서를 다른 문서로 바꿀 수 있습니다.
예시
다음 코드는 cuisine 필드에 "Pizza" 값이 있는 restaurants 컬렉션의 첫 번째 문서를 대체합니다. 교체 후 이 문서에는 값이 "Mongo's Pizza"인 name 필드가 있고 address 및 borough 필드에 대한 새 값이 있습니다.
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 filtervar oldPizzaRestaurant = _restaurantsCollection.Find(filter).First();var oldId = oldPizzaRestaurant.Id;
// Generates a new restaurant documentRestaurant newPizzaRestaurant = new(){ Id = oldId, Name = "Mongo's Pizza", Cuisine = "Pizza", Address = new Address() { Street = "Pizza St", ZipCode = "10003" }, Borough = "Manhattan",};
// Asynchronously replaces the existing restaurant document with the new documentreturn 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 filtervar oldPizzaRestaurant = _restaurantsCollection.Find(filter).First();var oldId = oldPizzaRestaurant.Id;
// Generates a new restaurant documentRestaurant newPizzaRestaurant = new(){ Id = oldId, Name = "Mongo's Pizza", Cuisine = "Pizza", Address = new Address() { Street = "Pizza St", ZipCode = "10003" }, Borough = "Manhattan",};
// Replaces the existing restaurant document with the new documentreturn _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant);ReplaceOne() 작업의 완전히 실행 가능한 예시는 ReplaceOne 코드 샘플를 참조하세요.
예상 결과
앞의 전체 예시 중 하나를 실행하면 다음과 같은 결과가 나옵니다.
First pizza restaurant before replacement: J&V Famous PizzaRestaurants modified by replacement: 1First pizza restaurant after replacement: Mongo's PizzaResetting sample data...done.추가 정보
문서 교체에 대해 자세히 학습 문서 교체 가이드 참조하세요.
빌더 사용에 대해 자세히 알아보려면 빌더를 사용한 작업을 참조하세요.