Skip to content

Commit b05951f

Browse files
Change streams
1 parent bf9b873 commit b05951f

File tree

2 files changed

+400
-0
lines changed

2 files changed

+400
-0
lines changed
Lines changed: 300 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,300 @@
1+
.. _csharp-change-streams:
2+
3+
====================
4+
Monitor Data Changes
5+
====================
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: watch, code example
19+
20+
Overview
21+
--------
22+
23+
In this guide, you can learn how to use a **change stream** to monitor real-time
24+
changes to your database. A change stream is a {+mdb-server+} feature that
25+
allows your application to subscribe to data changes on a collection, database,
26+
or deployment.
27+
28+
Sample Data
29+
~~~~~~~~~~~
30+
31+
The examples in this guide use the ``sample_restaurants.restaurants`` collection
32+
from the :atlas:`Atlas sample datasets </sample-data>`. To learn how to create a
33+
free MongoDB Atlas cluster and load the sample datasets, see the :ref:`<csharp-quickstart>`.
34+
35+
The examples on this page use the following ``Restaurant``, ``Address``, and ``GradeEntry``
36+
classes as models:
37+
38+
.. literalinclude:: /includes/code-examples/Restaurant.cs
39+
:language: csharp
40+
:copyable:
41+
:dedent:
42+
43+
.. literalinclude:: /includes/code-examples/Address.cs
44+
:language: csharp
45+
:copyable:
46+
:dedent:
47+
48+
.. literalinclude:: /includes/code-examples/GradeEntry.cs
49+
:language: csharp
50+
:copyable:
51+
:dedent:
52+
53+
.. include:: /includes/convention-pack-note.rst
54+
55+
Open a Change Stream
56+
--------------------
57+
58+
To open a change stream, call the ``Watch()`` or ``WatchAsync()`` method. The instance on which you
59+
call the method determines the scope of events that the change
60+
stream listens for. You can call the ``Watch()`` or ``WatchAsync()`` method on the following
61+
classes:
62+
63+
- ``MongoClient``: To monitor all changes in the MongoDB deployment
64+
- ``Database``: To monitor changes in all collections in the database
65+
- ``Collection``: To monitor changes in the collection
66+
67+
The following example opens a change stream on the ``restaurants`` collection
68+
and outputs the type of changes as they occur. Select the
69+
:guilabel:`Asynchronous` or :guilabel:`Synchronous` tab to see the corresponding
70+
code.
71+
72+
.. tabs::
73+
74+
.. tab:: Asynchronous
75+
:tabid: change-stream-async
76+
77+
.. literalinclude:: /includes/code-examples/change-streams/change-streams.cs
78+
:start-after: start-open-change-stream-async
79+
:end-before: end-open-change-stream-async
80+
:language: csharp
81+
82+
.. tab:: Synchronous
83+
:tabid: change-stream-sync
84+
85+
.. literalinclude:: /includes/code-examples/change-streams/change-streams.cs
86+
:start-after: start-open-change-stream
87+
:end-before: end-open-change-stream
88+
:language: csharp
89+
90+
To begin watching for changes, run the application. Then, in a separate
91+
application or shell, modify the ``restaurants`` collection. The following
92+
example updates a document with a ``name`` field value of ``Blarney Castle``:
93+
94+
.. _csharp-change-stream-update:
95+
96+
.. literalinclude:: /includes/code-examples/change-streams/change-streams.cs
97+
:start-after: start-modify-document
98+
:end-before: end-modify-document
99+
:language: csharp
100+
101+
When you update the collection, the change stream application prints the type of change
102+
as it occurs.
103+
104+
Modify the Change Stream Output
105+
-------------------------------
106+
107+
You can pass the ``pipeline`` parameter to the ``Watch()`` and ``WatchAsync()``
108+
methods to modify the change stream output. This parameter allows you to watch
109+
for only specified change events. Format the parameter as a list of objects that
110+
each represent an aggregation stage.
111+
112+
You can specify the following stages in the ``pipeline`` parameter:
113+
114+
- ``$addFields``
115+
- ``$match``
116+
- ``$project``
117+
- ``$replaceRoot``
118+
- ``$replaceWith``
119+
- ``$redact``
120+
- ``$set``
121+
- ``$unset``
122+
123+
The following example uses the ``pipeline`` parameter to open a change stream
124+
that records only update operations. Select the :guilabel:`Asynchronous` or :guilabel:`Synchronous` tab to see the
125+
corresponding code.
126+
127+
.. tabs::
128+
129+
.. tab:: Asynchronous
130+
:tabid: change-stream-async
131+
132+
.. literalinclude:: /includes/code-examples/change-streams/change-streams.cs
133+
:start-after: start-change-stream-pipeline-async
134+
:end-before: end-change-stream-pipeline-async
135+
:language: csharp
136+
137+
.. tab:: Synchronous
138+
:tabid: change-stream-sync
139+
140+
.. literalinclude:: /includes/code-examples/change-streams/change-streams.cs
141+
:start-after: start-change-stream-pipeline
142+
:end-before: end-change-stream-pipeline
143+
:language: csharp
144+
145+
To learn more about modifying your change stream output, see the
146+
:manual:`Modify Change Stream Output
147+
</changeStreams/#modify-change-stream-output>` section in the {+mdb-server+}
148+
manual.
149+
150+
Modify ``Watch()`` Behavior
151+
---------------------------
152+
153+
The ``Watch()`` and ``WatchAsync`` methods accept optional parameters, which represent
154+
options you can use to configure the operation. If you don't specify any
155+
options, the driver does not customize the operation.
156+
157+
The following table describes the options you can set to customize the behavior
158+
of ``Watch()`` and ``WatchAsync()``:
159+
160+
.. list-table::
161+
:widths: 30 70
162+
:header-rows: 1
163+
164+
* - Property
165+
- Description
166+
167+
* - ``FullDocument``
168+
- | Specifies whether to show the full document after the change, rather
169+
than showing only the changes made to the document. To learn more about
170+
this option, see :ref:`csharp-change-stream-pre-post-image`.
171+
172+
* - ``FullDocumentBeforeChange``
173+
- | Specifies whether to show the full document as it was before the change, rather
174+
than showing only the changes made to the document. To learn more about
175+
this option, see :ref:`csharp-change-stream-pre-post-image`.
176+
177+
* - ``ResumeAfter``
178+
- | Directs ``Watch()`` or ``WatchAsync()`` to resume returning changes after the
179+
operation specified in the resume token.
180+
| Each change stream event document includes a resume token as the ``_id``
181+
field. Pass the entire ``_id`` field of the change event document that
182+
represents the operation you want to resume after.
183+
| ``ResumeAfter`` is mutually exclusive with ``StartAfter`` and ``StartAtOperationTime``.
184+
185+
* - ``StartAfter``
186+
- | Directs ``Watch()`` or ``WatchAsync()`` to start a new change stream after the
187+
operation specified in the resume token. Allows notifications to
188+
resume after an invalidate event.
189+
| Each change stream event document includes a resume token as the ``_id``
190+
field. Pass the entire ``_id`` field of the change event document that
191+
represents the operation you want to resume after.
192+
| ``StartAfter`` is mutually exclusive with ``ResumeAfter`` and ``StartAtOperationTime``.
193+
194+
* - ``StartAtOperationTime``
195+
- | Directs ``Watch()`` or ``WatchAsync()`` to return only events that occur after the
196+
specified timestamp.
197+
| ``StartAtOperationTime`` is mutually exclusive with ``ResumeAfter`` and ``StartAfter``.
198+
199+
* - ``MaxAwaitTime``
200+
- | The maximum amount of time, in milliseconds, the server waits for new
201+
data changes to report to the change stream cursor before returning an
202+
empty batch. Defaults to 1000 milliseconds.
203+
204+
* - ``ShowExpandedEvents``
205+
- | Starting in {+mdb-server+} v6.0, change streams support change notifications
206+
for Data Definition Language (DDL) events, such as the ``createIndexes`` and ``dropIndexes`` events. To
207+
include expanded events in a change stream, create the change stream
208+
cursor and set this parameter to ``True``.
209+
210+
* - ``BatchSize``
211+
- | The maximum number of change events to return in each batch of the
212+
response from the MongoDB cluster.
213+
214+
* - ``Collation``
215+
- | The collation to use for the change stream cursor.
216+
217+
* - ``Comment``
218+
- | A comment to attach to the operation.
219+
220+
.. _csharp-change-stream-pre-post-image:
221+
222+
Include Pre-Images and Post-Images
223+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
224+
225+
.. important::
226+
227+
You can enable pre-images and post-images on collections only if your
228+
deployment uses MongoDB v6.0 or later.
229+
230+
By default, when you perform an operation on a collection, the
231+
corresponding change event includes only the delta of the fields
232+
modified by that operation. To see the full document before or after a
233+
change, specify the ``FullDocumentBeforeChange`` or the ``FullDocument``
234+
parameters in the ``Watch()`` or ``WatchAsync()`` method.
235+
236+
The **pre-image** is the full version of a document *before* a change. To include the
237+
pre-image in the change stream event, set the ``FullDocumentBeforeChange``
238+
parameter to one of the following values:
239+
240+
- ``WhenAvailable``: The change event includes a pre-image of the
241+
modified document for change events only if the pre-image is available.
242+
- ``Required``: The change event includes a pre-image of the
243+
modified document for change events. If the pre-image is not available, the
244+
driver raises an error.
245+
246+
The **post-image** is the full version of a document *after* a change. To include the
247+
post-image in the change stream event, set the ``full_document`` parameter to
248+
one of the following values:
249+
250+
- ``UpdateLookup``: The change event includes a copy of the entire changed
251+
document from some time after the change.
252+
- ``WhenAvailable``: The change event includes a post-image of the
253+
modified document for change events only if the post-image is available.
254+
- ``Required``: The change event includes a post-image of the
255+
modified document for change events. If the post-image is not available, the
256+
driver raises an error.
257+
258+
The following example opens a change stream on a collection and includes the post-image
259+
of updated documents by specifying the ``FullDocument`` parameter. Select the
260+
:guilabel:`Asynchronous` or :guilabel:`Synchronous` tab to see the corresponding
261+
code.
262+
263+
.. tabs::
264+
265+
.. tab:: Asynchronous
266+
:tabid: change-stream-async
267+
268+
.. literalinclude:: /includes/code-examples/change-streams/change-streams.cs
269+
:start-after: start-change-stream-post-image-async
270+
:end-before: end-change-stream-post-image-async
271+
:language: csharp
272+
273+
.. tab:: Synchronous
274+
:tabid: change-stream-sync
275+
276+
.. literalinclude:: /includes/code-examples/change-streams/change-streams.cs
277+
:start-after: start-change-stream-post-image
278+
:end-before: end-change-stream-post-image
279+
:language: csharp
280+
281+
To learn more about pre-images and post-images, see
282+
:manual:`Change Streams with Document Pre- and Post-Images </changeStreams#change-streams-with-document-pre--and-post-images>`
283+
in the {+mdb-server+} manual.
284+
285+
Additional Information
286+
----------------------
287+
288+
To learn more about change streams, see :manual:`Change Streams
289+
</changeStreams>` in the {+mdb-server+} manual.
290+
291+
API Documentation
292+
~~~~~~~~~~~~~~~~~
293+
294+
To learn more about any of the methods or types discussed in this
295+
guide, see the following API documentation:
296+
297+
- `Watch() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoClient.Watch.html>`__
298+
- `WatchAsync() <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.IMongoClient.WatchAsync.html>`__
299+
- `ChangeStreamOptions <{+new-api-root+}/MongoDB.Driver/MongoDB.Driver.ChangeStreamOptions.html>`__
300+
- `UpdateOne() <{+new-api-root+}MongoDB.Driver/MongoDB.Driver.IMongoCollectionExtensions.UpdateOne.html>`__

0 commit comments

Comments
 (0)