Docs Menu

문서 교체

이 가이드 에서는 .NET/ C# 드라이버 사용하여 MongoDB 컬렉션 의 문서를 교체하는 방법을 학습 수 있습니다.

.NET/ C# 드라이버 ReplaceOne()ReplaceOneAsync() 메서드를 제공합니다. 이 메서드는 검색 기준과 일치하는 첫 번째 문서 에서 모든 필드( _id 필드 제외)를 제거 다음 지정한 필드와 값을 문서 에 삽입합니다.

참고

메서드 오버로드

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

이 가이드의 예에서는 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 클러스터를 생성하고 이 샘플 데이터를 로드하는 방법을 알아보세요.

컬렉션 의 문서 바꾸려면 ReplaceOne() 또는 ReplaceOneAsync() 메서드를 호출합니다. 이러한 메서드는 다음 매개변수를 허용합니다.

Parameter
설명

filter

바꿀 문서 지정하는 쿼리 필터하다 입니다. Builders 클래스를 사용하여 쿼리 필터하다 만들 수 있습니다. 쿼리 필터에 대한 자세한 내용은 MongoDB Server 매뉴얼을 참조하세요.

데이터 유형: FilterDefinition<TDocument>

replacement

새 문서에 삽입할 필드와 값을 지정하는 대체 문서입니다. 컬렉션의 문서가 C# 클래스에 매핑된 경우 대체 문서는 이 클래스의 인스턴스가 될 수 있습니다.

데이터 유형: TDocument

options

선택 사항. 바꾸기 작업에 대한 구성을 지정하는 ReplaceOptions 클래스의 인스턴스 . 기본값 은 null입니다.

데이터 유형: ReplaceOptions

cancellationToken

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

데이터 유형: 취소 토큰

다음 코드 예시 바꾸기 작업을 수행하는 방법을 보여 줍니다. 이 코드는 다음 단계를 수행합니다.

  1. Builders 클래스를 사용하여 쿼리 필터하다 만듭니다. 이 필터하다 cuisine 필드 값이 "Pizza"인 모든 문서와 일치합니다.

  2. Restaurant 객체 만듭니다.

  3. restaurants 컬렉션 에서 ReplaceOne() 메서드를 호출합니다. 이 작업은 컬렉션 에서 일치하는 첫 번째 문서 찾아 새로 만든 문서 로 바꿉니다.

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

// 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 Address()
{
Street = "Pizza St",
ZipCode = "10003"
},
Borough = "Manhattan",
};
// Replaces the existing restaurant document with the new document
return _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant);
// 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 Address()
{
Street = "Pizza St",
ZipCode = "10003"
},
Borough = "Manhattan",
};
// Asynchronously replaces the existing restaurant document with the new document
return await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant);

중요

_id 필드의 값은 변경할 수 없습니다. 대체 문서에서 _id 필드 값을 지정하는 경우 기존 문서의 _id 값과 일치해야 합니다.

교체 문서 _id 필드 의 값이 지정되지 않은 경우 POCO(Plain Old CLR/Class Object)의 _id 필드 에 [BsonIgnoreIfDefault] 속성을 추가할 수 있습니다. POCO의 _id 필드 ObjectId 유형인 경우 [BsonIgnoreIfDefault] 를 사용합니다.

다음 예시 이 속성을 추가하는 방법을 보여줍니다.

public class Restaurant
{
[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
// Other properties
}

ReplaceOne()ReplaceOneAsync() 메서드는 선택적으로 ReplaceOptions 객체 매개 변수로 허용하며, 이는 대체 작업을 구성하는 데 사용할 수 있는 옵션을 나타냅니다.

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

속성
설명

BypassDocumentValidation

바꾸기 작업에서 문서 유효성 검사 우회할지 여부를 지정합니다. 이를 통해 스키마 유효성 검사 요구 사항을 충족하지 않는 문서(있는 경우)를 대체할 수 있습니다. 스키마 유효성 검사 에 대한 자세한 내용은 MongoDB Server 매뉴얼을 참조하세요.

데이터 유형: bool?

Collation

결과를 정렬할 때 사용할 언어 데이터 정렬의 종류를 지정합니다. 데이터 정렬에 대한 자세한 내용은 MongoDB Server 매뉴얼을 참조하세요.

데이터 유형: 데이터 정렬

Comment

작업에 대해 사용자가 제공한 설명을 가져오거나 설정합니다. 자세한 내용은 MongoDB Server 매뉴얼을 참조하세요.

데이터 유형: BsonValue

Hint

문서를 스캔하는 데 사용할 인덱스 를 가져오거나 설정합니다. 자세한 내용은 MongoDB Server 매뉴얼을 참조하세요.

데이터 유형: BsonValue

IsUpsert

쿼리 필터하다 와 일치하는 문서가 없는 경우 대체 작업에서 업서트 작업을 수행할지 여부를 지정합니다. 자세한 내용은 MongoDB Server 매뉴얼을 참조하세요.

데이터 유형: bool

Let

let 문서 가져오거나 설정합니다. 자세한 내용은 MongoDB Server 매뉴얼을 참조하세요.

데이터 유형: BsonDocument

다음 예시 앞의 예시 와 동일한 단계를 수행하지만 BypassDocumentValidation 옵션을 사용하여 스키마 유효성 검사 요구 사항을 우회합니다. Synchronous 또는 Asynchronous 탭 선택하여 해당 코드를 확인합니다.

// 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 Address()
{
Street = "Pizza St",
ZipCode = "10003"
},
Borough = "Manhattan",
};
var options = new ReplaceOptions
{
BypassDocumentValidation = true
};
// Replaces the existing restaurant document with the new document
return _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant, options);
// 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 Address()
{
Street = "Pizza St",
ZipCode = "10003"
},
Borough = "Manhattan",
};
var options = new ReplaceOptions
{
BypassDocumentValidation = true
};
// Asynchronously replaces the existing restaurant document with the new document
return await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant, options);

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

속성
설명

IsAcknowledged

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

데이터 유형: bool

IsModifiedCountAvailable

ReplaceOneResult에서 대체된 기록 수를 읽을 수 있는지 여부를 나타냅니다.

데이터 유형: bool

MatchedCount

쿼리 필터가 대체되었는지 여부에 관계없이 쿼리 필터와 일치하는 문서 수입니다.

데이터 유형: long

ModifiedCount

대체 작업으로 바뀐 문서 수입니다.

데이터 유형: long

UpsertedId

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

데이터 유형: BsonValue

이 페이지에 사용된 메서드 및 클래스에 대해 자세히 학습 다음 API 설명서를 참조하세요.