Docs Menu
Docs Home
/ / /
C#/ .NET 드라이버
/

데이터 변경 사항 모니터링

이 가이드 에서는 변경 스트림 을 사용하여 데이터의 실시간 변경 사항을 모니터 하는 방법을 학습 수 있습니다. 변경 스트림 은 애플리케이션 이 컬렉션, 데이터베이스 또는 배포서버 서버의 데이터 변경 사항을 구독 할 수 있도록 하는 MongoDB Server 기능 입니다.

이 가이드 의 예제에서는 sample_restaurants.restaurants Atlas 샘플 데이터 세트의 컬렉션 사용합니다. 무료 MongoDB Atlas cluster 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 .NET/ C# 드라이버 시작하기 를 참조하세요.

이 페이지의 예시에서는 다음 Restaurant, AddressGradeEntry 클래스를 모델로 사용합니다:

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 클래스의 속성에 매핑합니다.

사용자 지정 직렬화에 대해 자세히 알아보려면 사용자 지정 직렬화를참조하세요.

변경 스트림 을 열려면 Watch() 또는 WatchAsync() 메서드를 호출합니다. 메서드를 호출하는 인스턴스 에 따라 변경 스트림 이 수신 대기하는 이벤트 범위가 결정됩니다. 다음 클래스에서 Watch() 또는 WatchAsync() 메서드를 호출할 수 있습니다.

  • MongoClient: MongoDB deployment의 모든 변경 사항을 모니터링합니다.

  • Database: 데이터베이스에 있는 모든 컬렉션의 변경 사항을 모니터링합니다.

  • Collection: 컬렉션의 변경 사항을 모니터링합니다.

다음 예시 에서는 restaurants 컬렉션 에서 변경 스트림 을 열고 변경 사항이 발생할 때 출력합니다. Synchronous 또는 Asynchronous 탭 을 선택하여 해당 코드를 확인합니다.

var database = client.GetDatabase("sample_restaurants");
var collection = database.GetCollection<Restaurant>("restaurants");
// Opens a change stream and prints the changes as they're received
using (var cursor = collection.Watch())
{
foreach (var change in cursor.ToEnumerable())
{
Console.WriteLine("Received the following type of change: " + change.BackingDocument);
}
}
var database = client.GetDatabase("sample_restaurants");
var collection = database.GetCollection<Restaurant>("restaurants");
// Opens a change streams and print the changes as they're received
using var cursor = await collection.WatchAsync();
await cursor.ForEachAsync(change =>
{
Console.WriteLine("Received the following type of change: " + change.BackingDocument);
});

변경 사항을 확인하려면 애플리케이션 을 실행 합니다. 그런 다음 별도의 애플리케이션 또는 shell 에서 restaurants 컬렉션 을 수정합니다. "name" 값이 "Blarney Castle" 인 문서 를 업데이트하면 다음과 같은 변경 스트림 출력이 생성됩니다.

{ "_id" : { "_data" : "..." }, "operationType" : "update", "clusterTime" : Timestamp(...),
"wallTime" : ISODate("..."), "ns" : { "db" : "sample_restaurants", "coll" : "restaurants" },
"documentKey" : { "_id" : ObjectId("...") }, "updateDescription" : { "updatedFields" : { "cuisine" : "Irish" },
"removedFields" : [], "truncatedArrays" : [] } }

pipeline 매개변수를 Watch()WatchAsync() 메서드에 전달하여 변경 스트림 출력을 수정할 수 있습니다. 이 매개변수를 사용하면 지정된 변경 이벤트만 감시할 수 있습니다. EmptyPipelineDefinition 클래스를 사용하고 관련 집계 단계 메서드를 추가하여 파이프라인 을 만듭니다.

pipeline 매개변수에 다음과 같은 집계 단계를 지정할 수 있습니다.

  • $addFields

  • $changeStreamSplitLargeEvent

  • $match

  • $project

  • $replaceRoot

  • $replaceWith

  • $redact

  • $set

  • $unset

클래스를 사용하여 집계 파이프라인 빌드 방법을 학습 빌더를 사용한 작업 가이드 의 집계 PipelineDefinitionBuilder 파이프라인 단계를 참조하세요.

변경 스트림 출력 수정에 대해 자세히 알아보려면 MongoDB Server 매뉴얼의 변경 스트림 출력 수정 섹션을 참조하세요.

다음 예시 에서는 pipeline 매개 변수를 사용하여 업데이트 작업만 기록하는 변경 스트림 을 엽니다. Synchronous 또는 Asynchronous 탭 을 선택하여 해당 코드를 확인합니다.

var pipeline = new EmptyPipelineDefinition<ChangeStreamDocument<Restaurant>>()
.Match(change => change.OperationType == ChangeStreamOperationType.Update);
// Opens a change streams and print the changes as they're received
using (var cursor = collection.Watch(pipeline))
{
foreach (var change in cursor.ToEnumerable())
{
Console.WriteLine("Received the following change: " + change);
}
}
var pipeline = new EmptyPipelineDefinition<ChangeStreamDocument<Restaurant>>()
.Match(change => change.OperationType == ChangeStreamOperationType.Update);
// Opens a change stream and prints the changes as they're received
using (var cursor = await collection.WatchAsync(pipeline))
{
await cursor.ForEachAsync(change =>
{
Console.WriteLine("Received the following change: " + change);
});
}

애플리케이션 크기가 16 MB를 초과하는 변경 이벤트를 생성하는 경우 서버 BSONObjectTooLarge 오류를 반환합니다. 이 오류를 방지하려면 $changeStreamSplitLargeEvent 파이프라인 단계를 사용하여 이벤트를 더 작은 조각으로 분할 수 있습니다. .NET/ C# 드라이버 집계 API 에는 변경 스트림 파이프라인 에 $changeStreamSplitLargeEvent 단계를 추가하는 데 사용할 수 있는 ChangeStreamSplitLargeEvent() 메서드가 포함되어 있습니다.

이 예시 운전자 변경 사항을 감시하고 16 MB 제한을 초과하는 변경 이벤트를 분할 지시합니다. 이 코드는 각 이벤트 에 대한 변경 문서 출력하고 헬퍼 메서드를 호출하여 이벤트 조각을 다시 조립합니다.

var pipeline = new EmptyPipelineDefinition<ChangeStreamDocument<Restaurant>>()
.ChangeStreamSplitLargeEvent();
using var cursor = collection.Watch(pipeline);
foreach (var completeEvent in GetNextChangeStreamEvent(cursor.ToEnumerable().GetEnumerator()))
{
Console.WriteLine("Received the following change: " + completeEvent.BackingDocument);
}
var pipeline = new EmptyPipelineDefinition<ChangeStreamDocument<Restaurant>>()
.ChangeStreamSplitLargeEvent();
using var cursor = await collection.WatchAsync(pipeline);
await foreach (var completeEvent in GetNextChangeStreamEventAsync(cursor))
{
Console.WriteLine("Received the following change: " + completeEvent.BackingDocument);
}

참고

앞의 예시 와 같이 변경 이벤트 프래그먼트를 리어셈블하는 것이 좋지만 이 단계는 선택 사항입니다. 동일한 로직을 사용하여 분할 및 전체 변경 이벤트를 모두 볼 수 있습니다.

앞의 예시 에서는 GetNextChangeStreamEvent(), GetNextChangeStreamEventAsync()MergeFragment() 메서드를 사용하여 변경 이벤트 조각을 단일 변경 스트림 문서 로 리어셈블합니다. 다음 코드는 이러한 메서드를 정의합니다.

// Fetches the next complete change stream event
private static IEnumerable<ChangeStreamDocument<TDocument>> GetNextChangeStreamEvent<TDocument>(
IEnumerator<ChangeStreamDocument<TDocument>> changeStreamEnumerator)
{
while (changeStreamEnumerator.MoveNext())
{
var changeStreamEvent = changeStreamEnumerator.Current;
if (changeStreamEvent.SplitEvent != null)
{
var fragment = changeStreamEvent;
while (fragment.SplitEvent.Fragment < fragment.SplitEvent.Of)
{
changeStreamEnumerator.MoveNext();
fragment = changeStreamEnumerator.Current;
MergeFragment(changeStreamEvent, fragment);
}
}
yield return changeStreamEvent;
}
}
// Merges a fragment into the base event
private static void MergeFragment<TDocument>(
ChangeStreamDocument<TDocument> changeStreamEvent,
ChangeStreamDocument<TDocument> fragment)
{
foreach (var element in fragment.BackingDocument)
{
if (element.Name != "_id" && element.Name != "splitEvent")
{
changeStreamEvent.BackingDocument[element.Name] = element.Value;
}
}
}
// Fetches the next complete change stream event
private static async IAsyncEnumerable<ChangeStreamDocument<TDocument>> GetNextChangeStreamEventAsync<TDocument>(
IAsyncCursor<ChangeStreamDocument<TDocument>> changeStreamCursor)
{
var changeStreamEnumerator = GetNextChangeStreamEventFragmentAsync(changeStreamCursor).GetAsyncEnumerator();
while (await changeStreamEnumerator.MoveNextAsync())
{
var changeStreamEvent = changeStreamEnumerator.Current;
if (changeStreamEvent.SplitEvent != null)
{
var fragment = changeStreamEvent;
while (fragment.SplitEvent.Fragment < fragment.SplitEvent.Of)
{
await changeStreamEnumerator.MoveNextAsync();
fragment = changeStreamEnumerator.Current;
MergeFragment(changeStreamEvent, fragment);
}
}
yield return changeStreamEvent;
}
}
private static async IAsyncEnumerable<ChangeStreamDocument<TDocument>> GetNextChangeStreamEventFragmentAsync<TDocument>(
IAsyncCursor<ChangeStreamDocument<TDocument>> changeStreamCursor)
{
while (await changeStreamCursor.MoveNextAsync())
{
foreach (var changeStreamEvent in changeStreamCursor.Current)
{
yield return changeStreamEvent;
}
}
}
// Merges a fragment into the base event
private static void MergeFragment<TDocument>(
ChangeStreamDocument<TDocument> changeStreamEvent,
ChangeStreamDocument<TDocument> fragment)
{
foreach (var element in fragment.BackingDocument)
{
if (element.Name != "_id" && element.Name != "splitEvent")
{
changeStreamEvent.BackingDocument[element.Name] = element.Value;
}
}
}

대규모 변경 이벤트 분할에 대해 자세히 학습 MongoDB Server 매뉴얼에서 $changeStreamSplitLargeEvent를 참조하세요.

Watch()WatchAsync() 메서드는 작업을 구성하는 데 사용할 수 있는 옵션을 나타내는 선택적 매개변수를 허용합니다. 옵션을 지정하지 않으면 운전자 는 작업을 사용자 지정하지 않습니다.

다음 표에서는 Watch()WatchAsync() 의 동작을 사용자 지정하기 위해 설정하다 수 있는 옵션에 대해 설명합니다.

옵션
설명

FullDocument

Specifies whether to show the full document after the change, rather than showing only the changes made to the document. To learn more about this option, see Include Pre-Images and Post-Images.

FullDocumentBeforeChange

Specifies whether to show the full document as it was before the change, rather than showing only the changes made to the document. To learn more about this option, see Include Pre-Images and Post-Images.

ResumeAfter

Directs Watch() or WatchAsync() to resume returning changes after the operation specified in the resume token.
Each change stream event document includes a resume token as the _id field. Pass the entire _id field of the change event document that represents the operation you want to resume after.
ResumeAfter is mutually exclusive with StartAfter and StartAtOperationTime.

StartAfter

Directs Watch() or WatchAsync() to start a new change stream after the operation specified in the resume token. Allows notifications to resume after an invalidate event.
Each change stream event document includes a resume token as the _id field. Pass the entire _id field of the change event document that represents the operation you want to resume after.
StartAfter is mutually exclusive with ResumeAfter and StartAtOperationTime.

StartAtOperationTime

Directs Watch() or WatchAsync() to return only events that occur after the specified timestamp.
StartAtOperationTime is mutually exclusive with ResumeAfter and StartAfter.

MaxAwaitTime

Specifies the maximum amount of time, in milliseconds, the server waits for new data changes to report to the change stream cursor before returning an empty batch. Defaults to 1000 milliseconds.

ShowExpandedEvents

Starting in MongoDB Server v6.0, change streams support change notifications for Data Definition Language (DDL) events, such as the createIndexes and dropIndexes events. To include expanded events in a change stream, create the change stream cursor and set this parameter to True.

batchSize

Specifies the maximum number of documents that a change stream can return in each batch, which applies to Watch() or WatchAsync(). If the batchSize option is not set, watch functions have an initial batch size of 101 documents and a maximum size of 16 mebibytes (MiB) for each subsequent batch. This option can enforce a smaller limit than 16 MiB, but not a larger one. If you set batchSize to a limit that result in batches larger than 16 MiB, this option has no effect and Watch() or WatchAsync() uses the default batch size.

Collation

Specifies the collation to use for the change stream cursor. See the Collation section of this page for more information.

Comment

Attaches a comment to the operation.

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

다음 표에서는 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

(Optional) Specifies whether to include case comparison.

When this argument is true, the driver's behavior depends on the value of the strength argument:

- If strength is CollationStrength.Primary, the driver compares base characters and case.
- If strength is CollationStrength.Secondary, the driver compares base characters, diacritics, other secondary differences, and case.
- If strength is any other value, this argument is ignored.

When this argument is false, the driver doesn't include case comparison at strength level Primary or Secondary.

Data Type: boolean
Default: false

CaseLevel

caseFirst

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

Default: CollationCaseFirst.Off

CaseFirst

strength

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

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.

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.

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

(Optional) Specifies whether strings containing diacritics sort from the back of the string to the front.

Data Type: boolean
Default: false

Backwards

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

중요

배포에서 MongoDB v6.0 이상을 사용하는 경우에만 컬렉션에서 사전 이미지 및 사후 이미지를 활성화할 수 있습니다.

기본값 으로 컬렉션 에서 작업을 수행할 때 해당 변경 이벤트 에는 해당 작업에 의해 수정된 필드의 델타만 포함됩니다. 변경 전후의 전체 문서 를 보려면 ChangeStreamOptions 객체 를 만들고 FullDocumentBeforeChange 또는 FullDocument 옵션을 지정합니다. 그런 다음 ChangeStreamOptions 객체 를 Watch() 또는 WatchAsync() 메서드에 전달합니다.

사전 이미지 는 변경 전의 문서 전체 버전입니다. 변경 스트림 이벤트 에 사전 이미지를 포함하려면 FullDocumentBeforeChange 옵션을 다음 값 중 하나로 설정하다 합니다.

  • ChangeStreamFullDocumentBeforeChangeOption.WhenAvailable: 변경 이벤트에는 사전 이미지를 사용할 수 있는 경우에만 변경 이벤트에 대해 수정된 문서의 사전 이미지가 포함됩니다.

  • ChangeStreamFullDocumentBeforeChangeOption.Required: 변경 이벤트에는 변경 이벤트에 대한 수정된 문서의 사전 이미지가 포함됩니다. 사전 이미지를 사용할 수 없는 경우 드라이버에서 오류가 발생합니다.

사후 이미지 는 변경 문서 의 전체 버전입니다. 변경 스트림 이벤트 에 사후 이미지를 포함하려면 FullDocument 옵션을 다음 값 중 하나로 설정하다 합니다.

  • ChangeStreamFullDocumentOption.UpdateLookup: 변경 이벤트에는 변경 후 일정 시간 이후의 변경된 문서 전체의 복사본이 포함됩니다.

  • ChangeStreamFullDocumentOption.WhenAvailable: 변경 이벤트에는 사후 이미지를 사용할 수 있는 경우에만 변경 이벤트에 대해 수정된 문서의 사후 이미지가 포함됩니다.

  • ChangeStreamFullDocumentOption.Required: 변경 이벤트에는 변경 이벤트에 대한 수정된 문서의 사후 이미지가 포함됩니다. 사후 이미지를 사용할 수 없는 경우 드라이버에서 오류가 발생합니다.

다음 예시 에서는 컬렉션 에서 변경 스트림 을 열고 FullDocument 옵션을 지정하여 업데이트된 문서의 사후 이미지를 포함합니다. Synchronous 또는 Asynchronous 탭 을 선택하여 해당 코드를 확인합니다.

var pipeline = new EmptyPipelineDefinition<ChangeStreamDocument<Restaurant>>()
.Match(change => change.OperationType == ChangeStreamOperationType.Update);
var options = new ChangeStreamOptions
{
FullDocument = ChangeStreamFullDocumentOption.UpdateLookup,
};
using (var cursor = collection.Watch(pipeline, options))
{
foreach (var change in cursor.ToEnumerable())
{
Console.WriteLine(change.FullDocument.ToBsonDocument());
}
}
var pipeline = new EmptyPipelineDefinition<ChangeStreamDocument<Restaurant>>()
.Match(change => change.OperationType == ChangeStreamOperationType.Update);
var options = new ChangeStreamOptions
{
FullDocument = ChangeStreamFullDocumentOption.UpdateLookup,
};
using var cursor = await collection.WatchAsync(pipeline, options);
await cursor.ForEachAsync(change =>
{
Console.WriteLine(change.FullDocument.ToBsonDocument());
});

앞의 코드 예시 를 실행하고 "name" 값이 "Blarney Castle" 인 문서 를 업데이트하면 다음과 같은 변경 스트림 출력이 생성됩니다.

{ "_id" : ObjectId("..."), "name" : "Blarney Castle", "restaurant_id" : "40366356",
"cuisine" : "Traditional Irish", "address" : { "building" : "202-24", "coord" : [-73.925044200000002, 40.5595462],
"street" : "Rockaway Point Boulevard", "zipcode" : "11697" }, "borough" : "Queens", "grades" : [...] }

사전 이미지 및 사후 이미지에 대해 자세히 알아보려면 Change Streams 매뉴얼에서 문서 사전 및 사후 이미지로 MongoDB Server 을 참조하세요.

변경 스트림에 대해 자세히 알아보려면 Change Streams 매뉴얼의 MongoDB Server 을 참조하세요.

이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.

돌아가기

모니터링

이 페이지의 내용