Docs Home → Develop Applications → MongoDB Drivers → Node.js
Watch for Changes
Open a Change Stream
You can watch for changes in MongoDB using the watch()
method on the
following objects:
For each object, the watch()
method opens a change stream to
emit change event documents when they occur.
The watch()
method optionally takes an aggregation pipeline which consists of an array of aggregation stages
as the first parameter. The aggregation stages filter and transform the change events.
In the following snippet, the $match
stage matches all change event documents with a runtime
value of less than
15, filtering all others out.
const pipeline = [ { $match: { runtime: { $lt: 15 } } } ]; const changeStream = collection.watch(pipeline);
The watch()
method accepts an options
object as the second parameter. Refer to the links at the end of this
section for more information on the settings you can configure with this object.
The watch()
method returns an instance of a ChangeStream. You can read events from
change streams by iterating over them or listening for events. Select the tab that corresponds to the way you want to
read events from the change stream below.
Warning
Using a ChangeStream
in EventEmitter
and Iterator
mode
concurrently is not supported by the driver and causes an error. This
is to prevent undefined behavior, where the driver cannot guarantee
which consumer receives documents first.
Visit the following resources for additional material on the classes and methods presented above:
Example
The following example opens a change stream on the haikus
collection in
the insertDB
database. Let's create a listener function to receive and
print change events that occur on the collection.
First, open the change stream on the collection and then define a callback
on the change stream using the on()
method. Once set, generate a change
event by performing a change to the collection.
To generate the change event on the collection, let's use insertOne()
method to add a new document. Since the insertOne()
may run before the
listener function can register, we use a timer, defined as
simulateAsyncPause
to wait 1 second before executing the insert.
We also use simulateAsyncPause
after the insertion of the document
to provide ample time for the listener function to receive the change
event and for the callback to complete its execution before
closing the ChangeStream
instance using the close()
method.
The timers used in this example are only necessary for this demonstration to make sure there is enough time to register listener and have the callback process the event before exiting.
Note
You can use this example to connect to an instance of MongoDB and interact with a database that contains sample data. To learn more about connecting to your MongoDB instance and loading a sample dataset, see the Usage Examples guide.
Note
Identical Code Snippets
The JavaScript and TypeScript code snippets above are identical. There are no TypeScript specific features of the driver relevant to this use case.
If you run the preceding example, you should see the following output:
received a change to the collection: { _id: { _data: '825EC...' }, operationType: 'insert', clusterTime: new Timestamp { ... }, fullDocument: { _id: new ObjectId(...), title: 'Record of a Shriveled Datum', content: 'No bytes, no problem. Just insert a document, in MongoDB' }, ns: { db: 'insertDB', coll: 'haikus' }, documentKey: { _id: new ObjectId(...) } } closed the change stream
Note
Receive Full Documents From Updates
Change events that contain information on update operations only return the modified
fields by default rather than the full updated document. You can configure
your change stream to also return the most current version of the document
by setting the fullDocument
field of the options object to
"updateLookup"
as follows:
const options = { fullDocument: "updateLookup" }; // This could be any pipeline. const pipeline = []; const changeStream = collection.watch(pipeline, options);