Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js Driver

Watch for Changes

You can watch for changes in MongoDB using the watch() method on the following objects:

  • Collection

  • Database

  • MongoClient

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 = myColl.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:

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.

The following example opens a change stream on the haikus collection in the insertDB database and prints change events as they occur:

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.

When you run this code and then make a change to the haikus collection, such as performing an insert or delete operation, you can see the change event document printed in your terminal.

For example, if you insert a document to the collection, the code prints the following output:

Received change:
{
_id: {
_data: '...'
},
operationType: 'insert',
clusterTime: new Timestamp({ t: 1675800603, i: 31 }),
fullDocument: {
_id: new ObjectId("..."),
...
},
ns: { db: 'insertDB', coll: 'haikus' },
documentKey: { _id: new ObjectId("...") }
}

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 = myColl.watch(pipeline, options);

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 listener on the change stream using the on() method. Once you set the listener, generate a change event by performing a change to the collection.

To generate the change event on the collection, let's use the insertOne() method to add a new document. Since 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. This provides ample time for the listener function to receive the change event and for the listener to complete its execution before closing the ChangeStream instance using the close() method.

Note

Reason to include timers

The timers used in this example are only for demonstration purposes. They make sure that there is enough time to register the listener and have the listener process the change event before exiting.

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.

Visit the following resources for more material on the classes and methods mentioned on this page:

←  Run a CommandPerform Bulk Operations →