db.watch()

Definition

  • db.watch(pipeline, options)
  • For replica sets and sharded clusters only

New in version 4.0: Requires featureCompatibilityVersion (fCV) set to"4.0" or greater. For more information on fCV, seesetFeatureCompatibilityVersion.

Opens a change stream cursor for a databaseto report on all its non-system collections.

ParameterTypeDescriptionpipelinearrayAggregation pipeline consistingof one or more of the following aggregation stages:

Starting in MongoDB 4.2, change streams will throw an exception ifthe change stream aggregation pipeline modifies an event’s _id field.optionsdocumentOptional. Additional options that modify the behavior ofdb.watch().

You must pass an empty array [] to the pipeline parameter ifyou are not specifying a pipeline but are passing the optionsdocument.

The options document can contain the following fields and values:

FieldTypeDescriptionresumeAfterdocumentOptional. Directs db.watch() to attempt resumingnotifications starting after the operation specified in the resumetoken.

Each change stream event document includes a resume token as theid field. Pass the _entire _id field of the change eventdocument that represents the operation you want to resume after.

resumeAfter is mutually exclusive with startAfter andstartAtOperationTime.startAfterdocumentOptional. Directs db.watch() to attempt starting a new change streamafter the operation specified in the resume token. Allowsnotifications to resume after an invalidate event.

Each change stream event document includes a resume token as theid field. Pass the _entire _id field of the change eventdocument that represents the operation you want to resume after.

startAfter is mutually exclusive with resumeAfter andstartAtOperationTime.

New in version 4.2.

fullDocumentstringOptional. By default, db.watch() returns the delta ofthose fields modified by an update operation, instead of the entireupdated document.

Set fullDocument to "updateLookup" to directdb.watch() to look up the most currentmajority-committed version of the updated document.db.watch() returns a fullDocument field withthe document lookup in addition to the updateDescription delta.batchSizeintOptional. Specifies the maximum number of change events to return in eachbatch of the response from the MongoDB cluster.

Has the same functionality as cursor.batchSize().maxAwaitTimeMSintOptional. The maximum amount of time in milliseconds the server waits for newdata changes to report to the change stream cursor before returning anempty batch.

Defaults to 1000 milliseconds.collationdocumentOptional. Pass a collation documentto specify a collation for thechange stream cursor.

If omitted, defaults to simple binary comparison.startAtOperationTimeTimestampOptional. The starting point for the change stream. If the specified startingpoint is in the past, it must be in the time range of the oplog. Tocheck the time range of the oplog, seers.printReplicationInfo().

startAtOperationTime is mutually exclusive with resumeAfterand startAfter.

Returns:A cursor over the change event documents.See Change Events for examples of changeevent documents.

See also

db.collection.watch() and Mongo.watch()

Availability

Deployment

db.watch() is available for replica sets and shardedclusters:

  • For a replica set, you can issue db.watch() on anydata-bearing member.
  • For a sharded cluster, you must issue db.watch() on amongos instance.

Storage Engine

You can only use db.watch() with the Wired Tigerstorage engine.

Read Concern majority Support

Starting in MongoDB 4.2, change streams areavailable regardless of the "majority" read concernsupport; that is, read concern majority support can be eitherenabled (default) or disabledto use change streams.

In MongoDB 4.0 and earlier, change streams areavailable only if "majority" read concern support isenabled (default).

Behavior

  • You cannot run db.watch() on the admin, local, orconfig database.
  • db.watch() only notifies on data changes that havepersisted to a majority of data-bearing members.
  • The change stream cursor remains open untilone of the following occurs:
    • The cursor is explicitly closed.
    • An invalidate event occurs; forexample, a collection drop or rename.
    • The connection to the MongoDB deployment is closed.
    • If the deployment is a sharded cluster, a shard removal may cause anopen change stream cursor to close, and the closed change stream cursor maynot be fully resumable.
  • You can run db.watch() for a database that does not exist.However, once the database is created and you drop the database, thechange stream cursor closes.

Resumability

Unlike the MongoDB drivers, themongo shell does not automatically attempt to resume achange stream cursor after an error. The MongoDB drivers make _one_attempt to automatically resume a change stream cursor after certainerrors.

db.watch() uses information stored in the oplog to produce thechange event description and generate a resume token associated tothat operation. If the operation identified by the resume tokenpassed to the resumeAfter or startAfter option has alreadydropped off the oplog, db.watch() cannot resume thechange stream.

See Resume a Change Stream for more information onresuming a change stream.

Note

  • You cannot use resumeAfter to resume a change stream after aninvalidate event (for example, a collectiondrop or rename) closes the stream. Starting in MongoDB 4.2, you can usestartAfter to start a new changestream after an invalidate event.
  • If the deployment is a sharded cluster, a shard removal may cause anopen change stream cursor to close, and the closed change stream cursor maynot be fully resumable.

Full Document Lookup of Update Operations

By default, the change stream cursor returnsspecific field changes/deltas for update operations. You can alsoconfigure the change stream to look up and return the currentmajority-committed version of the changed document. Depending on otherwrite operations that may have occurred between the update and thelookup, the returned document may differ significantly from thedocument at the time of the update.

Depending on the number of changes applied during the update operationand the size of the full document, there is a risk that the size of thechange event document for an update operation is greater than the 16MBBSON document limit. If this occurs, the server closes the change streamcursor and returns an error.

Access Control

When running with access control, the user must have thefind and changeStream privilege actions onthe database resource. That is, a user musthave a role that grants the following privilege:

  1. { resource: { db: <dbname>, collection: "" }, actions: [ "find", "changeStream"] }

The built-in read role provides the appropriateprivileges.

Example

The following operation in the mongo shell opens achange stream cursor on the hr database. The returned cursorreports on data changes to all the non-system collections in thatdatabase.

  1. watchCursor = db.getSiblingDB("hr").watch()

Iterate the cursor to check for new events. Use thecursor.isExhausted() method to ensure the loop only exitsif the change stream cursor is closed and there are no objectsremaining in the latest batch:

  1. while (!watchCursor.isExhausted()){
  2. if (watchCursor.hasNext()){
  3. printjson(watchCursor.next());
  4. }
  5. }

For complete documentation on change stream output, seeChange Events.