개요
이 가이드 에서는 MongoDB .NET/ C# 드라이버 사용하여 여러 문서의 값을 업데이트 방법을 학습 수 있습니다.
.NET/ C# 드라이버 다음 메서드를 제공하여 값을 업데이트 .
UpdateMany(): 여러 문서에서 하나 이상의 필드를 업데이트합니다.UpdateManyAsync():UpdateMany()의 비동기 버전입니다.
다음 섹션에서는 이러한 메서드에 대해 자세히 설명합니다.
참고
메서드 오버로드
이 페이지의 많은 메서드에는 여러 개의 오버로드가 있습니다. 이 가이드 의 예제에서는 각 메서드에 대한 정의를 하나만 보여줍니다. 사용 가능한 오버로드에 대한 자세한 내용은 API 설명서를 참조하세요.
중요
입력 유효성 검사
빌더 클래스와 LINQ 쿼리는 기본 MongoDB 작업에 값을 전달합니다. 의도적으로 이러한 API는 보안 삭제 계층이 아닙니다. 애플리케이션 에서 신뢰할 수 없는 입력을 빌더나 LINQ 쿼리 에 전달하기 전에 유효성을 검사하고 삭제하세요.
샘플 데이터
이 가이드의 예에서는 sample_restaurants 데이터베이스의 restaurants 컬렉션을 사용합니다. 이 컬렉션의 문서는 다음 Restaurant, Address, GradeEntry 클래스를 모델로 사용합니다.
public class Restaurant { public ObjectId Id { get; set; } public string Name { get; set; } [] public string RestaurantId { get; set; } public string Cuisine { get; set; } public Address Address { get; set; } public string Borough { get; set; } public List<GradeEntry> Grades { get; set; } }
public class Address { public string Building { get; set; } [] public double[] Coordinates { get; set; } public string Street { get; set; } [] public string ZipCode { get; set; } }
public class GradeEntry { public DateTime Date { get; set; } public string Grade { get; set; } public float? Score { get; set; } }
참고
restaurants 컬렉션 의 문서는 대소문자 명명 규칙을 사용합니다. 이 가이드 의 예제에서는 ConventionPack 를 사용하여 컬렉션 의 필드를 파스칼식 대/소문자로 역직렬화하고 Restaurant 클래스의 속성에 매핑합니다.
사용자 지정 직렬화에 대해 자세히 알아보려면 사용자 지정 직렬화를참조하세요.
이 컬렉션 Atlas 에서 제공하는 샘플 데이터 세트에서 가져온 것입니다. 무료 MongoDB cluster 생성하고 이 샘플 데이터를 로드하는 방법을 학습 .NET/ C# 드라이버 시작하기 를 참조하세요.
메서드 및 매개변수
UpdateMany() 및 UpdateManyAsync() 메서드는 다음 매개변수를 허용합니다.
Parameter | 설명 |
|---|---|
| 업데이트 할 문서를 지정하는 데이터 유형: FilterDefinition |
|
데이터 유형: UpdateDefinition<TDocument> |
| Optional. An instance of the 데이터 유형: UpdateOptions |
| 선택 사항. 작업을 취소하는 데 사용할 수 있는 토큰입니다. 데이터 유형: |
여러 값 업데이트
UpdateMany() 및 UpdateManyAsync() 메서드는 각각 하나의 UpdateDefinition 객체 만 허용합니다. 다음 섹션에서는 단일 메서드 호출로 여러 값을 업데이트 방법을 설명합니다.
결합된 업데이트 정의
Builders.Update.Combine() 메서드를 사용하면 여러 UpdateDefinition 객체를 결합할 수 있습니다. 이 메서드는 다음 매개변수를 허용합니다.
Parameter | 설명 |
|---|---|
| 결합할 업데이트 정의의 배열 . 데이터 유형: |
Combine() 메서드는 여러 업데이트 작업을 정의하는 단일 UpdateDefinition 객체 반환합니다.
다음 코드 예시 메서드를 사용하여 Combine() $ 설정하다 작업과 $unset 작업을 결합합니다.
var filter = Builders<Restaurant>.Filter .Eq("cuisine", "Pizza"); var combinedUpdate = Builders<Restaurant>.Update.Combine( Builders<Restaurant>.Update.Set("cuisine", "French"), Builders<Restaurant>.Update.Unset("borough") ); _restaurantsCollection.UpdateMany(filter, combinedUpdate);
var filter = Builders<Restaurant>.Filter .Eq("cuisine", "Pizza"); var combinedUpdate = Builders<Restaurant>.Update.Combine( Builders<Restaurant>.Update.Set("cuisine", "French"), Builders<Restaurant>.Update.Unset("borough") ); await _restaurantsCollection.UpdateManyAsync(filter, combinedUpdate);
파이프라인 업데이트
일련의 업데이트 작업을 단일 집계 파이프라인으로 결합할 수 있습니다.
업데이트 파이프라인 만들려면 Builders.Update.Pipeline() 메서드를 호출합니다. 이 메서드는 다음 매개변수를 허용합니다.
Parameter | 설명 |
|---|---|
| 업데이트 파이프라인 나타내는 데이터 유형: |
Pipeline() 메서드는 여러 집계 단계를 정의하는 단일 UpdateDefinition 객체 반환합니다.
다음 코드 예시 메서드를 사용하여 Pipeline() $ 설정하다 작업과 $unset 작업을 결합합니다.
var filter = Builders<Restaurant>.Filter .Eq("cuisine", "Pizza"); var updatePipeline = Builders<Restaurant>.Update.Pipeline( PipelineDefinition<Restaurant, Restaurant>.Create( new BsonDocument("$set", new BsonDocument("cuisine", "French")), new BsonDocument("$unset", "borough") ) ); _restaurantsCollection.UpdateMany(filter, updatePipeline);
var filter = Builders<Restaurant>.Filter .Eq("cuisine", "Pizza"); var updatePipeline = Builders<Restaurant>.Update.Pipeline( PipelineDefinition<Restaurant, Restaurant>.Create( new BsonDocument("$set", new BsonDocument("cuisine", "French")), new BsonDocument("$unset", "borough") ) ); await _restaurantsCollection.UpdateManyAsync(filter, updatePipeline);
참고
지원되지 않는 작업
Update pipelines don't support all update operations, but they do support certain aggregation stages not found in other update definitions. For a list of update operations supported by pipelines, see Updates with Aggregation Pipeline in the MongoDB Server manual.
구성 옵션
UpdateMany() 및 UpdateManyAsync() 메서드는 선택적으로 UpdateOptions 객체 매개 변수로 허용합니다. 이 인수를 사용하여 업데이트 작업을 구성할 수 있습니다.
UpdateOptions 클래스에는 다음과 같은 속성이 포함되어 있습니다.
속성 | 설명 | ||||
|---|---|---|---|---|---|
| Specifies which array elements to modify for an update operation on an array field. See the MongoDB Server manual for more information. 데이터 유형: IEnumerable<ArrayFilterDefinition> | ||||
| Specifies whether the update operation bypasses document validation. This lets you update documents that don't meet the schema validation requirements, if any exist. See the MongoDB Server manual for more information on schema validation. 데이터 유형: | ||||
| 결과를 정렬할 때 사용할 언어 데이터 정렬의 종류를 지정합니다. 자세한 내용은 이 페이지의 데이터 정렬 섹션을 참조하세요. 데이터 유형: 데이터 정렬 | ||||
| Gets or sets the user-provided comment for the operation. See the MongoDB Server manual for more information. 데이터 유형: BsonValue | ||||
| Gets or sets the index to use to scan for documents. See the MongoDB Server manual for more information. 데이터 유형: BsonValue | ||||
| Specifies whether the update operation performs an upsert operation if no documents match the query filter. See the MongoDB Server manual for more information. 데이터 유형: | ||||
| 업데이트 작업은 지정된 정렬 순서의 첫 번째 문서 업데이트하므로 쿼리 여러 문서를 선택하는 경우 작업을 업데이트할 문서 를 결정합니다. 이 옵션을 설정하다 하려면 다음 코드와 같이 데이터를 모델링하는 일반 유형을 사용하는 데이터 유형: | ||||
| Gets or sets the let document. See the MongoDB Server manual for more information. 데이터 유형: BsonDocument |
데이터 정렬
작업에 대한 데이터 정렬을 구성하려면 데이터 정렬 클래스의 인스턴스를 만듭니다.
다음 표에서는 Collation 생성자가 허용하는 매개변수에 대해 설명합니다. 또한 각 설정의 값을 읽는 데 사용할 수 있는 해당 클래스 속성 도 나열되어 있습니다.
Parameter | 설명 | 클래스 속성 |
|---|---|---|
| Specifies the International Components for Unicode (ICU) locale. For a list of supported locales, see Collation Locales and Default Parameters in the MongoDB Server Manual. |
|
| (선택 사항) 대/소문자 비교 포함 여부를 지정합니다. |
|
| (Optional) Specifies the sort order of case differences during tertiary level comparisons. |
|
| (Optional) Specifies the level of comparison to perform, as defined in the ICU documentation. |
|
| (선택 사항) |
|
| (Optional) Specifies whether the driver considers whitespace and punctuation as base characters for purposes of comparison. |
|
| (Optional) Specifies which characters the driver considers ignorable when the |
|
| (Optional) Specifies whether the driver normalizes text as needed. |
|
| (선택 사항) 분음 부호가 포함된 string이 string의 뒤쪽에서 앞쪽으로 정렬되는지 지정합니다. |
|
데이터 정렬에 대한 자세한 내용은 MongoDB Server 매뉴얼의 데이터 정렬 페이지를 참조하세요.
반환 값
UpdateMany() 메서드는 UpdateResult을 반환하고, UpdateManyAsync() 메서드는 Task<UpdateResult> 객체 반환합니다. UpdateResult 클래스에는 다음과 같은 속성이 포함되어 있습니다.
속성 | 설명 |
|---|---|
| MongoDB에서 업데이트 작업을 승인했는지 여부를 나타냅니다. 데이터 유형: |
|
데이터 유형: |
| 업데이트 여부에 관계없이 쿼리 필터하다 와 일치하는 문서 수입니다. 데이터 유형: |
| 업데이트 작업으로 수정된 문서 수입니다. 데이터 유형: |
| 드라이버가 업서트를 수행한 경우 데이터베이스에 업서트된 문서의 ID입니다. 데이터 유형: BsonValue |
추가 정보
이 페이지에는 UpdateManyAsync() 메서드를 사용하여 데이터를 수정하는 방법을 보여주는 짧은 인터랙티브 실습이 포함되어 있습니다. MongoDB 또는 코드 편집기를 설치하지 않고도 브라우저 창에서 직접 이 실습을 완료할 수 있습니다.
실습을 시작하려면 페이지 상단에 있는 Open Interactive Tutorial 버튼을 클릭하세요. 실습을 전체 화면 형식으로 확장하려면 랩 창의 오른쪽 상단 모서리에 있는 전체 화면 버튼(⛶)을 클릭합니다.
업데이트 작업의 실행 가능한 예제는 다음 사용 예제를 참조하세요.
쿼리 필터 만들기에 대해 자세히 학습 쿼리 필터 만들기 가이드 참조하세요.
API 문서
이 가이드 에 설명된 메서드 또는 유형에 대한 자세한 내용은 다음 API 문서를 참조하세요.