AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

UpdateOne

이 가이드 에서는 MongoDB .NET/ C# 드라이버 사용하여 단일 문서 에서 값을 업데이트 방법을 학습 수 있습니다.

.NET/ C# 드라이버 다음 메서드를 제공하여 값을 업데이트 .

  • UpdateOne(): 단일 문서 에서 하나 이상의 필드를 업데이트합니다.

  • UpdateOneAsync(): UpdateOne()의 비동기 버전입니다.

다음 섹션에서는 이러한 메서드에 대해 자세히 설명합니다.

참고

메서드 오버로드

이 페이지의 많은 메서드에는 여러 개의 오버로드가 있습니다. 이 가이드 의 예제에서는 각 메서드에 대한 정의를 하나만 보여줍니다. 사용 가능한 오버로드에 대한 자세한 내용은 API 설명서를 참조하세요.

중요

입력 유효성 검사

빌더 클래스와 LINQ 쿼리는 기본 MongoDB 작업에 값을 전달합니다. 의도적으로 이러한 API는 보안 삭제 계층이 아닙니다. 애플리케이션 에서 신뢰할 수 없는 입력을 빌더나 LINQ 쿼리 에 전달하기 전에 유효성을 검사하고 삭제하세요.

이 가이드의 예에서는 sample_restaurants 데이터베이스의 restaurants 컬렉션을 사용합니다. 이 컬렉션의 문서는 다음 Restaurant, Address, GradeEntry 클래스를 모델로 사용합니다.

public class Restaurant
{
public ObjectId Id { get; set; }
public string Name { get; set; }
[BsonElement("restaurant_id")]
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; }
[BsonElement("coord")]
public double[] Coordinates { get; set; }
public string Street { get; set; }
[BsonElement("zipcode")]
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# 드라이버 시작하기 를 참조하세요.

UpdateOne()UpdateOneAsync() 메서드는 다음 매개변수를 허용합니다.

Parameter
설명

filter

업데이트 할 문서 지정하는 FilterDefinition 클래스의 인스턴스 . 쿼리 필터하다 만드는 방법을 학습하려면 쿼리 필터 만들기를 참조하세요.

데이터 유형: FilterDefinition

update

UpdateDefinition 클래스의 인스턴스 . 이 객체 업데이트 작업의 종류, 업데이트 할 필드, 각 필드 의 새 값을 지정합니다. 객체 를 만드는 방법을 학습 UpdateDefinition 하나의 문서에서 필드 업데이트하나의 문서에서 배열 업데이트를 참조하세요.

데이터 유형: UpdateDefinition<TDocument>

options

Optional. An instance of the UpdateOptions class that specifies the configuration for the update operation. The default value is null. For a list of available options, see Configuration Options.

데이터 유형: UpdateOptions

cancellationToken

선택 사항. 작업을 취소하는 데 사용할 수 있는 토큰입니다.

데이터 유형: CancellationToken

UpdateOne()UpdateOneAsync() 메서드는 각각 하나의 UpdateDefinition 객체 만 허용합니다. 다음 섹션에서는 단일 메서드 호출로 여러 값을 업데이트 방법을 설명합니다.

Builders.Update.Combine() 메서드를 사용하면 여러 UpdateDefinition 객체를 결합할 수 있습니다. 이 메서드는 다음 매개변수를 허용합니다.

Parameter
설명

updates

결합할 업데이트 정의의 배열 .

데이터 유형: UpdateDefinition<TDocument>[]

Combine() 메서드는 여러 업데이트 작업을 정의하는 단일 UpdateDefinition 객체 반환합니다.

다음 코드 예시 메서드를 사용하여 Combine() $ 설정하다 작업과 $unset 작업을 결합합니다.

var filter = Builders<Restaurant>.Filter
.Eq("name", "Downtown Deli");
var combinedUpdate = Builders<Restaurant>.Update.Combine(
Builders<Restaurant>.Update.Set("cuisine", "French"),
Builders<Restaurant>.Update.Unset("borough")
);
_restaurantsCollection.UpdateOne(filter, combinedUpdate);
var filter = Builders<Restaurant>.Filter
.Eq("name", "Downtown Deli");
var combinedUpdate = Builders<Restaurant>.Update.Combine(
Builders<Restaurant>.Update.Set("cuisine", "French"),
Builders<Restaurant>.Update.Unset("borough")
);
await _restaurantsCollection.UpdateOneAsync(filter, combinedUpdate);

일련의 업데이트 작업을 단일 집계 파이프라인으로 결합할 수 있습니다.

업데이트 파이프라인 만들려면 Builders.Update.Pipeline() 메서드를 호출합니다. 이 메서드는 다음 매개변수를 허용합니다.

Parameter
설명

pipeline

업데이트 파이프라인 나타내는 PipelineDefinition 인스턴스 입니다. PipelineDefinition 객체 생성하려면 수행하려는 각 업데이트 작업에 대한 BSON 문서 생성한 다음 이러한 문서를 PipelineDefinition.Create() 메서드에 전달합니다.

데이터 유형: PipelineDefinition<TDocument, TDocument>

Pipeline() 메서드는 여러 집계 단계를 정의하는 단일 UpdateDefinition 객체 반환합니다.

다음 코드 예시 메서드를 사용하여 Pipeline() $ 설정하다 작업과 $unset 작업을 결합합니다.

var filter = Builders<Restaurant>.Filter
.Eq("name", "Downtown Deli");
var updatePipeline = Builders<Restaurant>.Update.Pipeline(
PipelineDefinition<Restaurant, Restaurant>.Create(
new BsonDocument("$set", new BsonDocument("cuisine", "French")),
new BsonDocument("$unset", "borough")
)
);
_restaurantsCollection.UpdateOne(filter, updatePipeline);
var filter = Builders<Restaurant>.Filter
.Eq("name", "Downtown Deli");
var updatePipeline = Builders<Restaurant>.Update.Pipeline(
PipelineDefinition<Restaurant, Restaurant>.Create(
new BsonDocument("$set", new BsonDocument("cuisine", "French")),
new BsonDocument("$unset", "borough")
)
);
await _restaurantsCollection.UpdateOneAsync(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.

UpdateOne()UpdateOneAsync() 메서드는 선택적으로 UpdateOptions 객체 매개 변수로 허용합니다. 이 인수를 사용하여 업데이트 작업을 구성할 수 있습니다.

UpdateOptions 클래스에는 다음과 같은 속성이 포함되어 있습니다.

속성
설명

ArrayFilters

Specifies which array elements to modify for an update operation on an array field. See the MongoDB Server manual for more information.

데이터 유형: IEnumerable<ArrayFilterDefinition>

BypassDocumentValidation

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.

데이터 유형: bool?

Collation

결과를 정렬할 때 사용할 언어 데이터 정렬의 종류를 지정합니다. 자세한 내용은 이 페이지의 데이터 정렬 섹션을 참조하세요.

데이터 유형: 데이터 정렬

Comment

Gets or sets the user-provided comment for the operation. See the MongoDB Server manual for more information.

데이터 유형: BsonValue

Hint

Gets or sets the index to use to scan for documents. See the MongoDB Server manual for more information.

데이터 유형: BsonValue

IsUpsert

Specifies whether the update operation performs an upsert operation if no documents match the query filter. See the MongoDB Server manual for more information.

데이터 유형: bool

Sort

업데이트 작업은 지정된 정렬 순서의 첫 번째 문서 업데이트하므로 쿼리 여러 문서를 선택하는 경우 작업을 업데이트할 문서 를 결정합니다. 이 옵션을 설정하다 하려면 다음 코드와 같이 데이터를 모델링하는 일반 유형을 사용하는 UpdateOptions<T> 인스턴스 인스턴스화해야 합니다.

var options = new UpdateOptions<Restaurant>
{
Sort = Builders<Restaurant>.Sort.Ascending(r => r.Name)
};

데이터 유형: SortDefinition<T>

Let

Gets or sets the let document. See the MongoDB Server manual for more information.

데이터 유형: BsonDocument

작업에 대한 데이터 정렬을 구성하려면 데이터 정렬 클래스의 인스턴스를 만듭니다.

다음 표에서는 Collation 생성자가 허용하는 매개변수에 대해 설명합니다. 또한 각 설정의 값을 읽는 데 사용할 수 있는 해당 클래스 속성 도 나열되어 있습니다.

Parameter
설명
클래스 속성

locale

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.

If you want to use simple binary comparison, use the Collation.Simple static property to return a Collation object with the locale set to "simple".
Data Type: string

Locale

caseLevel

(선택 사항) 대/소문자 비교 포함 여부를 지정합니다.

이 인수가 true인 경우 드라이버의 동작은 strength 인수의 값에 따라 달라집니다.

- strengthCollationStrength.Primary인 경우 드라이버는 기본 문자와 대소문자를 비교합니다.
- strengthCollationStrength.Secondary인 경우 드라이버는 기본 문자, 발음 부호, 기타 세컨더리 차이 및 대소문자를 비교합니다.
- strength 이 기타 값인 경우 이 인수는 무시됩니다.

이 인수가 false인 경우 드라이버는 Primary 또는 Secondary 수준의 강도에서 대소문자 비교를 포함하지 않습니다.

데이터 유형: boolean
기본값: false

CaseLevel

caseFirst

(Optional) Specifies the sort order of case differences during tertiary level comparisons.

Data Type: CollationCaseFirst
Default: CollationCaseFirst.Off

CaseFirst

strength

(Optional) Specifies the level of comparison to perform, as defined in the ICU documentation.

Data Type: CollationStrength
Default: CollationStrength.Tertiary

Strength

numericOrdering

(Optional) Specifies whether the driver compares numeric strings as numbers.

If this argument is true, the driver compares numeric strings as numbers. For example, when comparing the strings "10" and "2", the driver treats the values as 10 and 2, and finds 10 to be greater.

If this argument is false or excluded, the driver compares numeric strings as strings. For example, when comparing the strings "10" and "2", the driver compares one character at a time. Because "1" is less than "2", the driver finds "10" to be less than "2".

For more information, see Collation Restrictions in the MongoDB Server manual.

Data Type: boolean
Default: false

NumericOrdering

alternate

(Optional) Specifies whether the driver considers whitespace and punctuation as base characters for purposes of comparison.

Data Type: CollationAlternate
Default: CollationAlternate.NonIgnorable (spaces and punctuation are considered base characters)

Alternate

maxVariable

(Optional) Specifies which characters the driver considers ignorable when the alternate argument is CollationAlternate.Shifted.

Data Type: CollationMaxVariable
Default: CollationMaxVariable.Punctuation (the driver ignores punctuation and spaces)

MaxVariable

normalization

(Optional) Specifies whether the driver normalizes text as needed.

Most text doesn't require normalization. For more information about normalization, see the ICU documentation.

Data Type: boolean
Default: false

Normalization

backwards

(선택 사항) 분음 부호가 포함된 string이 string의 뒤쪽에서 앞쪽으로 정렬되는지 지정합니다.

데이터 유형: boolean
기본값: false

Backwards

데이터 정렬에 대한 자세한 내용은 MongoDB Server 매뉴얼의 데이터 정렬 페이지를 참조하세요.

UpdateOne() 메서드는 UpdateResult을 반환하고, UpdateOneAsync() 메서드는 Task<UpdateResult> 객체 반환합니다. UpdateResult 클래스에는 다음과 같은 속성이 포함되어 있습니다.

속성
설명

IsAcknowledged

MongoDB에서 업데이트 작업을 승인했는지 여부를 나타냅니다.

데이터 유형: bool

IsModifiedCountAvailable

UpdateResult에서 업데이트 레코드 수를 읽을 수 있는지 여부를 나타냅니다.

데이터 유형: bool

MatchedCount

업데이트 여부에 관계없이 쿼리 필터하다 와 일치하는 문서 수입니다.

데이터 유형: long

ModifiedCount

업데이트 작업으로 수정된 문서 수입니다.

데이터 유형: long

UpsertedId

드라이버가 업서트를 수행한 경우 데이터베이스에 업서트된 문서의 ID입니다.

데이터 유형: BsonValue

업데이트 작업의 실행 가능한 예제는 다음 사용 예제를 참조하세요.

쿼리 필터 만들기에 대해 자세히 학습 쿼리 필터 만들기 가이드 참조하세요.

이 가이드 에 설명된 메서드 또는 유형에 대한 자세한 내용은 다음 API 문서를 참조하세요.