MongoCollection 객체에서 UpdateOne() 메서드를 사용하여 단일 문서를 업데이트할 수 있습니다. 이 메서드에는 업데이트할 문서를 지정하는 쿼리 필터와 드라이버가 쿼리 필터와 일치하는 첫 번째 문서에 적용해야 하는 변경 사항을 지정하는 업데이트 성명서가 필요합니다.
참고
UpdateOne() 메서드는 필터와 일치하는 첫 번째 문서만 업데이트합니다. 두 개 이상의 문서를 업데이트하려면 updateMany () 메서드를 사용하세요.
팁
UpdateOptions 인스턴스를 UpdateOne() 메서드에 전달하여 동작을 사용자 지정할 수 있습니다.
예시
다음 예제에서는 Builders를 사용하여 restaurants 컬렉션에 있는 첫 번째 문서 'Bagels N Buns'의 name을 '2 Bagels 2 Buns'로 업데이트합니다.
Asynchronous 또는 Synchronous 탭을 선택하여 해당 코드를 확인합니다.
// Creates a filter for all documents with a "name" of "Bagels N Buns"var filter = Builders<Restaurant>.Filter .Eq(restaurant => restaurant.Name, "Bagels N Buns");
// Creates instructions to update the "name" field of the first document// that matches the filtervar update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Name, "2 Bagels 2 Buns");
// Updates the first document that has a "name" value of "Bagels N Buns"return await _restaurantsCollection.UpdateOneAsync(filter, update);UpdateOneAsync() 작업의 완전히 실행 가능한 예시는 UpdateOneAsync 예제를 참조하세요.
// Creates a filter for all documents with a "name" of "Bagels N Buns"var filter = Builders<Restaurant>.Filter .Eq(restaurant => restaurant.Name, "Bagels N Buns");
// Creates instructions to update the "name" field of the first document// that matches the filtervar update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Name, "2 Bagels 2 Buns");
// Updates the first document that has a "name" value of "Bagels N Buns"return _restaurantsCollection.UpdateOne(filter, update);작업의 완전히 실행 가능한 예를 보려면 UpdateOne UpdateOneAsync() 예제를 참조하세요.
예상 결과
위의 전체 예시 중 하나를 실행한 후 UpdateOne()을 호출할 때마다 콘솔에 다음과 같은 내용이 기록됩니다.
Updated documents: 1팁
UpdateOne() , UpdateResult 객체를 반환합니다.
자세한 정보
문서 업데이트에 대한 자세한 내용은 Update One 가이드를 참조하세요.
빌더 사용에 대해 자세히 알아보려면 빌더를 사용한 작업을 참조하세요.