Skip to content

Commit 81036c2

Browse files
Mohammad Hunan Chughtaicbush
andauthored
(DOCSP-7905): Change Streams Usage Example (#52)
* added intro to changeStream section * init change stram commit * update toc tree * update verbiage * update link * updated verbiage * added code snippet * updated rst syn * updated verbiage * updated verbiage * updated verbiage * updated verbiage * updated link to node-api role * (DOCSP-7905): adopted node-api role * updated formatting * added link to promise def * fixed spacing * updated formatting * updated verbiage * fixed formatting * updated verbiage * updated verbiage * added dup page for rough draft purposes * added dup page for rough draft purposes * update change stream verbiage * Cleaned up formatting * updated copy for example * fixed formatting * updated formatting * added headers and updated verbiage * added headers and updated verbiage * Fixed formatting * removed unneeded var * update verbiage * update mdn link * added event emitter link and added verbiage fix * updated code * cleanup of doc * more formatting fixes * improve formatting * updated code snippet to remove specific uri and clean client * removed 'real-world' wording for PR comment * updated verbiage * update verbiage * update verbiage * update verbiage to address PR comments * update formatting * clarified code comment * (DOCSP-7905): updated verbiage to address pr comments * update example paragraph * update verbiage * update verbiage * update code * updated code comments * fixed spacing * fixed verbiage * fixed verbiage per commentS * Removed unneeded vars * update verbiage to address comments * fixed verbiage * Fix punctuation Co-Authored-By: Chris Bush <[email protected]> * Fix punctuation Co-Authored-By: Chris Bush <[email protected]> * fixed verbiage to adhere to PR comment * update verbiage * added additional links * updated more links * update highlighting * fixed quote mark * fixed verbiage for consistency * fixed formatting Co-authored-by: Chris Bush <[email protected]>
1 parent edf7402 commit 81036c2

File tree

3 files changed

+126
-0
lines changed

3 files changed

+126
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// ignored first line
2+
const { MongoClient } = require("mongodb");
3+
4+
// Replace the uri string with your MongoDB deployment's connection string.
5+
const uri =
6+
"mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&w=majority&useUnifiedTopology=true";
7+
8+
const client = new MongoClient(uri);
9+
10+
let changeStream;
11+
async function run() {
12+
try {
13+
await client.connect();
14+
const database = client.db("sample_mflix");
15+
const collection = database.collection("movies");
16+
17+
// open a Change Stream on the "movies" collection
18+
changeStream = collection.watch();
19+
20+
// set up a listener when change events are emitted
21+
changeStream.on("change", next => {
22+
// process any change event
23+
console.log("received a change to the collection: \t", next);
24+
});
25+
26+
// wrap the setTimeout methods in a new Promise to wait for the timers to run
27+
await new Promise(resolve => {
28+
// wait for the event listener to register before inserting a document
29+
setTimeout(async () => {
30+
await collection.insertOne({
31+
test: "sample movie document",
32+
});
33+
// wait to close `changeStream` after the listener receives the event
34+
setTimeout(async () => {
35+
resolve(await changeStream.close());
36+
}, 1000);
37+
}, 1000);
38+
});
39+
} finally {
40+
await client.close();
41+
}
42+
}
43+
run().catch(console.dir);

source/usage-examples.txt

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,21 @@ Usage Examples
44

55
.. default-domain:: mongodb
66

7+
:doc:`bulkWrite </usage-examples/bulkWrite>`
8+
:doc:`countDocuments and estimatedDocumentCount </usage-examples/count>`
9+
:doc:`deleteMany </usage-examples/deleteMany>`
10+
:doc:`insertOne </usage-examples/insertOne>`
11+
:doc:`deleteOne </usage-examples/deleteOne>`
12+
:doc:`find </usage-examples/find>`
13+
:doc:`findOne </usage-examples/findOne>`
14+
:doc:`insertMany </usage-examples/insertMany>`
15+
:doc:`updateOne</usage-examples/updateOne>`
16+
:doc:`updateMany</usage-examples/updateMany>`
17+
:doc:`replaceOne</usage-examples/replaceOne>`
18+
:doc:`distinct</usage-examples/distinct>`
19+
:doc:`command</usage-examples/command>`
20+
:doc:`changeStream</usage-examples/changeStream>`
21+
722
.. toctree::
823
:caption: Examples
924

@@ -15,4 +30,5 @@ Usage Examples
1530
/usage-examples/count
1631
/usage-examples/distinct
1732
/usage-examples/command
33+
/usage-examples/changeStream
1834
/usage-examples/bulkWrite
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
=================
2+
Watch for Changes
3+
=================
4+
5+
.. default-domain:: mongodb
6+
7+
Open a Change Stream
8+
--------------------
9+
10+
You can keep track of changes to data in MongoDB, such as changes to a
11+
collection, database, or deployment, by opening a :manual:`Change
12+
Stream</changeStreams/>`. A ``Change Stream`` allows applications to
13+
watch for changes to data and react to those changes. You can open a
14+
``Change Stream`` by calling the :node-api:`Collection.watch()
15+
</Collection.html#watch>`, :node-api:`Db.watch() </Db.html#watch>`, or
16+
:node-api:`MongoClient.watch()</MongoClient.html#watch>` method.
17+
18+
The ``watch()`` method optionally takes a :manual:`pipeline
19+
</reference/operator/aggregation-pipeline/>`, an array of
20+
:manual:`stages </changeStreams/#modify-change-stream-output>`, as the
21+
first parameter to filter the :manual:`change events
22+
</reference/change-events/>` output. Also, ``watch()`` can take an
23+
additional options object as the second parameter. Set the
24+
``fullDocument`` field of the additional options object to the string
25+
``"updateLookup"`` to receive an event that contains the changes to the
26+
document as well as the entire altered document. Alternatively, you can
27+
set ``fullDocument`` to the string ``"default"`` to only receive the
28+
altered document, but not the changes to the document.
29+
30+
Process the Change Stream Events
31+
--------------------------------
32+
33+
You can capture events from a ``Change Stream`` instance by using a listener
34+
function. Call the ``watch()`` command to get a ``Change Stream`` instance. Add
35+
your listener function by calling the `EventEmitter.on()
36+
<https://nodejs.org/api/events.html#events_emitter_on_eventname_listener>`_
37+
method on that instance. Set the value of the first parameter to the
38+
string ``'change'`` and add your :mdn:`callback function
39+
<Glossary/Callback_function>` as the second parameter. The callback
40+
triggers when a ``change event`` is emitted, providing the next available
41+
document. You can specify logic in the callback to process the event
42+
document when it is received.
43+
44+
Call the :node-api:`close() </ChangeStream.html#close>` method on the
45+
``Change Stream`` instance to stop processing ``change events``. This method
46+
closes the ``Change Stream`` and frees resources.
47+
48+
Example
49+
-------
50+
51+
The following example opens a ``Change Stream`` on the ``movies``
52+
collection. We create a listener function to receive and print change
53+
events that occur.
54+
55+
To emit a ``change event``, we perform a change to the collection, such as
56+
insertion with ``insertOne()``. To prevent ``insertOne()`` from
57+
executing before the listener function can register, we create a timer
58+
that uses :mdn:`setTimeout
59+
<Web/API/WindowOrWorkerGlobalScope/setTimeout>` to wait 1 second. When
60+
you insert a document, the listener receives the corresponding event.
61+
62+
After that, we create a second timer to wait an additional second after
63+
the insertion of the document to close the ``Change Stream`` instance
64+
using ``changeStream.close()``.
65+
66+
.. literalinclude:: /code-snippets/usage-examples/changeStream.js
67+
:language: javascript :linenos:

0 commit comments

Comments
 (0)