Docs Home → Develop Applications → MongoDB Manual
db.collection.watch()![](/zh-cn/docs/v5.3/assets/link.svg)
On this page
- Definition
- Availability
- Deployment
- Storage Engine
- Read Concern
majority
Support - Behavior
- Resumability
- Full Document Lookup of Update Operations
- Access Control
- Cursor Iteration
- Examples
- Open a Change Stream
- Change Stream with Full Document Update Lookup
- Change Stream with Aggregation Pipeline Filter
- Resuming a Change Stream
Definition![](/zh-cn/docs/v5.3/assets/link.svg)
db.collection.watch( pipeline, options )
Important
mongosh Method
This is a
mongosh
method. This is not the documentation forNode.js
or other programming language specific driver methods.In most cases,
mongosh
methods work the same way as the legacymongo
shell methods. However, some legacy methods are unavailable inmongosh
.For the legacy
mongo
shell documentation, refer to the documentation for the corresponding MongoDB Server release:For MongoDB API drivers, refer to the language specific MongoDB driver documentation.
For replica sets and sharded clusters only
Opens a change stream cursor on the collection.
ParameterTypeDescriptionpipeline
arrayOptional. An Aggregation Pipeline consisting of one or more of the following aggregation stages:
$replaceWith
(Available starting in MongoDB 4.2)$set
(Available starting in MongoDB 4.2)$unset
(Available starting in MongoDB 4.2)
Specify a pipeline to filter/modify the change events output.
Starting in MongoDB 4.2, change streams will throw an exception if the change stream aggregation pipeline modifies an event's _id field.
options
documentOptional. Additional options that modify the behavior ofwatch()
.The
options
document can contain the following fields and values:FieldTypeDescriptionresumeAfter
documentOptional. Directs
watch()
to attempt resuming notifications starting after the operation specified in the resume token.Each change stream event document includes a resume token as the
_id
field. Pass the entire_id
field of the change event document that represents the operation you want to resume after.resumeAfter
is mutually exclusive withstartAfter
andstartAtOperationTime
.startAfter
documentOptional. Directs
watch()
to attempt starting a new change stream after the operation specified in the resume token. Allows notifications to resume after an invalidate event.Each change stream event document includes a resume token as the
_id
field. Pass the entire_id
field of the change event document that represents the operation you want to resume after.startAfter
is mutually exclusive withresumeAfter
andstartAtOperationTime
.New in version 4.2.
fullDocument
stringOptional. By default,
watch()
returns the delta of those fields modified by an update operation, instead of the entire updated document.Set
fullDocument
to"updateLookup"
to directwatch()
to look up the most current majority-committed version of the updated document.watch()
returns afullDocument
field with the document lookup in addition to theupdateDescription
delta.batchSize
intOptional. Specifies the maximum number of change events to return in each batch of the response from the MongoDB cluster.
Has the same functionality as
cursor.batchSize()
.maxAwaitTimeMS
intOptional. The maximum amount of time in milliseconds the server waits for new data changes to report to the change stream cursor before returning an empty batch.
Defaults to
1000
milliseconds.collation
documentOptional. Pass a collation document to specify a collation for the change stream cursor.
Starting in MongoDB 4.2, defaults to
simple
binary comparison if omitted. In earlier versions, change streams opened on a single collection would inherit the collection's default collation.startAtOperationTime
TimestampOptional. The starting point for the change stream. If the specified starting point is in the past, it must be in the time range of the oplog. To check the time range of the oplog, see
rs.printReplicationInfo()
.startAtOperationTime
is mutually exclusive withresumeAfter
andstartAfter
.New in version 4.0.
Returns: A cursor that remains open as long as a connection to the MongoDB deployment remains open and the collection exists. See Change Events for examples of change event documents. Tip
See also:
Availability![](/zh-cn/docs/v5.3/assets/link.svg)
Deployment![](/zh-cn/docs/v5.3/assets/link.svg)
db.collection.watch()
is available for replica set and
sharded cluster deployments :
For a replica set, you can issue
db.collection.watch()
on any data-bearing member.For a sharded cluster, you must issue
db.collection.watch()
on amongos
instance.
Storage Engine![](/zh-cn/docs/v5.3/assets/link.svg)
You can only use db.collection.watch()
with the Wired
Tiger storage engine.
Read Concern majority
Support![](/zh-cn/docs/v5.3/assets/link.svg)
Starting in MongoDB 4.2, change streams are
available regardless of the "majority"
read concern
support; that is, read concern majority
support can be either
enabled (default) or disabled
to use change streams.
In MongoDB 4.0 and earlier, change streams are
available only if "majority"
read concern support is
enabled (default).
Behavior![](/zh-cn/docs/v5.3/assets/link.svg)
db.collection.watch()
only notifies on data changes that have persisted to a majority of data-bearing members.The change stream cursor remains open until one of the following occurs:
The cursor is explicitly closed.
An invalidate event occurs; for example, 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 an open change stream cursor to close, and the closed change stream cursor may not be fully resumable.
Resumability![](/zh-cn/docs/v5.3/assets/link.svg)
Unlike the MongoDB Drivers, mongosh
does
not automatically attempt to resume a change stream cursor after an
error. The MongoDB drivers make one attempt to automatically resume
a change stream cursor after certain errors.
db.collection.watch()
uses information stored in the oplog to produce the
change event description and generate a resume token associated to
that operation. If the operation identified by the resume token
passed to the resumeAfter
or startAfter
option has already
dropped off the oplog, db.collection.watch()
cannot resume the
change stream.
See Resume a Change Stream for more information on resuming a change stream.
Note
You cannot use
resumeAfter
to resume a change stream after an invalidate event (for example, a collection drop or rename) closes the stream. Starting in MongoDB 4.2, you can use startAfter to start a new change stream after an invalidate event.If the deployment is a sharded cluster, a shard removal may cause an open change stream cursor to close, and the closed change stream cursor may not be fully resumable.
Note
Resume Token
The resume token _data
type depends on the MongoDB versions and,
in some cases, the feature compatibility version (fcv) at the time
of the change stream's opening/resumption (i.e. a change in fcv
value does not affect the resume tokens for already opened change
streams):
MongoDB Version | Feature Compatibility Version | Resume Token _data Type |
---|---|---|
MongoDB 4.2 and later | "4.2" or "4.0" | Hex-encoded string ( v1 ) |
MongoDB 4.0.7 and later | "4.0" or "3.6" | Hex-encoded string ( v1 ) |
MongoDB 4.0.6 and earlier | "4.0" | Hex-encoded string ( v0 ) |
MongoDB 4.0.6 and earlier | "3.6" | BinData |
MongoDB 3.6 | "3.6" | BinData |
Hex Encoded Tokens![](/zh-cn/docs/v5.3/assets/link.svg)
With hex-encoded string resume tokens, you can compare and sort the resume tokens.
Regardless of the fcv value, a 4.0 deployment can use either BinData resume tokens or hex string resume tokens to resume a change stream. As such, a 4.0 deployment can use a resume token from a change stream opened on a collection from a 3.6 deployment.
New resume token formats introduced in a MongoDB version cannot be consumed by earlier MongoDB versions.
Decode Resume Tokens![](/zh-cn/docs/v5.3/assets/link.svg)
Full Document Lookup of Update Operations![](/zh-cn/docs/v5.3/assets/link.svg)
By default, the change stream cursor returns specific field changes/deltas for update operations. You can also configure the change stream to look up and return the current majority-committed version of the changed document. Depending on other write operations that may have occurred between the update and the lookup, the returned document may differ significantly from the document at the time of the update.
Depending on the number of changes applied during the update operation and the size of the full document, there is a risk that the size of the change event document for an update operation is greater than the 16MB BSON document limit. If this occurs, the server closes the change stream cursor and returns an error.
Access Control![](/zh-cn/docs/v5.3/assets/link.svg)
When running with access control, the user must have the
find
and changeStream
privilege actions on
the collection resource. That is, a user must
have a role that grants the following privilege:
{ resource: { db: <dbname>, collection: <collection> }, actions: [ "find", "changeStream" ] }
The built-in read
role provides the appropriate
privileges.
Cursor Iteration![](/zh-cn/docs/v5.3/assets/link.svg)
MongoDB provides multiple ways to iterate on a cursor.
The cursor.hasNext()
method blocks and waits for the next
event. To monitor the watchCursor
cursor and iterate over the
events, use hasNext()
like this:
while (!watchCursor.isClosed()) { if (watchCursor.hasNext()) { firstChange = watchCursor.next(); break; } }
The cursor.tryNext()
method is non-blocking. To monitor
the watchCursor
cursor and iterate over the events, use
tryNext()
like this:
while (!watchCursor.isClosed()) { let next = watchCursor.tryNext() while (next !== null) { printjson(next); next = watchCursor.tryNext() } }
Examples![](/zh-cn/docs/v5.3/assets/link.svg)
Open a Change Stream![](/zh-cn/docs/v5.3/assets/link.svg)
The following operation opens a change stream cursor against the
data.sensors
collection:
watchCursor = db.getSiblingDB("data").sensors.watch()
Iterate the cursor to check for new events. Use the
cursor.isClosed()
method with the cursor.tryNext()
method to ensure the loop only exits if the change stream cursor is
closed and there are no objects remaining in the latest batch:
while (!watchCursor.isClosed()) { let next = watchCursor.tryNext() while (next !== null) { printjson(next); next = watchCursor.tryNext() } }
For complete documentation on change stream output, see Change Events.
Change Stream with Full Document Update Lookup![](/zh-cn/docs/v5.3/assets/link.svg)
Set the fullDocument
option to "updateLookup"
to direct the
change stream cursor to lookup the most current majority-committed
version of the document associated to an update change stream event.
The following operation opens a change stream cursor against
the data.sensors
collection using the
fullDocument : "updateLookup"
option.
watchCursor = db.getSiblingDB("data").sensors.watch( [], { fullDocument : "updateLookup" } )
Iterate the cursor to check for new events. Use the
cursor.isClosed()
method with the cursor.tryNext()
method to ensure the loop only exits if the change stream cursor is
closed and there are no objects remaining in the latest batch:
while (!watchCursor.isClosed()) { let next = watchCursor.tryNext() while (next !== null) { printjson(next); next = watchCursor.tryNext() } }
For any update operation, the change event returns the result of the
document lookup in the fullDocument
field.
For an example of the full document update output, see change stream update event.
For complete documentation on change stream output, see Change Events.
Change Stream with Aggregation Pipeline Filter![](/zh-cn/docs/v5.3/assets/link.svg)
Note
Starting in MongoDB 4.2, change streams will throw an exception if the change stream aggregation pipeline modifies an event's _id field.
The following operation opens a change stream cursor against the
data.sensors
collection using an aggregation pipeline to
filter only insert
events:
watchCursor = db.getSiblingDB("data").sensors.watch( [ { $match : {"operationType" : "insert" } } ] )
Iterate the cursor to check for new events. Use the
cursor.isClosed()
method with the cursor.hasNext()
method to ensure the loop only exits if the change stream cursor is
closed and there are no objects remaining in the latest batch:
while (!watchCursor.isClosed()){ if (watchCursor.hasNext()){ printjson(watchCursor.next()); } }
The change stream cursor only returns change events where the
operationType
is insert
. For complete documentation on
change stream output, see Change Events.
Resuming a Change Stream![](/zh-cn/docs/v5.3/assets/link.svg)
Every document returned by a change stream cursor includes a resume
token as the _id
field. To resume a change stream, pass the entire
_id
document of the change event you want to resume from to
either the resumeAfter
or startAfter
option of
watch()
.
The following operation resumes a change stream cursor against the
data.sensors
collection using a resume token. This
assumes that the operation that generated the resume token has not
rolled off the cluster's oplog.
let watchCursor = db.getSiblingDB("data").sensors.watch(); let firstChange; while (!watchCursor.isClosed()) { if (watchCursor.hasNext()) { firstChange = watchCursor.next(); break; } } watchCursor.close(); let resumeToken = firstChange._id; resumedWatchCursor = db.getSiblingDB("data").sensors.watch( [], { resumeAfter : resumeToken } )
Iterate the cursor to check for new events. Use the
cursor.isClosed()
method with the cursor.hasNext()
method to ensure the loop only exits if the change stream cursor is
closed and there are no objects remaining in the latest batch:
while (!resumedWatchCursor.isClosed()){ if (resumedWatchCursor.hasNext()){ print(resumedWatchCursor.next()); } }
See Resume a Change Stream for complete documentation on resuming a change stream.