db.collection.watch()
On this page本页内容
Definition定义Availability可用性Deployment部署Storage Engine存储引擎Read Concern读取关注majority
Supportmajority
支持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 Streams with Document Pre- and Post-Images使用文档前后映像更改流Change Stream with Aggregation Pipeline Filter使用聚合管道筛选器更改流Resuming a Change Stream恢复更改流
Definition定义
db.collection.watch( pipeline, options )
- Important
mongosh Method
This page documents a
mongosh
method. This is not the documentation for database commands or language-specific drivers, such as Node.js.For the database command, see the
aggregate
command with the$changeStream
aggregation stage.For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.
For the legacy
mongo
shell documentation, refer to the documentation for the corresponding MongoDB Server release:For replica sets and sharded clusters only仅适用于复制集和分片集群Opens a change stream cursor on the collection.在集合上打开更改流游标。Parameter参数Type类型Description描述pipeline
array Optional.可选的。An Aggregation Pipeline consisting of one or more of the following aggregation stages:由以下一个或多个聚合阶段组成的聚合管道:$addFields
$match
$project
$replaceRoot
$replaceWith
(Available starting in MongoDB 4.2)(从MongoDB 4.2开始提供)$redact
$set
(Available starting in MongoDB 4.2)(从MongoDB 4.2开始提供)$unset
(Available starting in MongoDB 4.2)(从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.从MongoDB 4.2开始,如果变更流聚合管道修改了事件的_id
字段,则变更流将抛出异常。options
document Optional.可选的。Additional options that modify the behavior of修改watch()
.watch()
行为的其他选项。Theoptions
document can contain the following fields and values:options
文档可以包含以下字段和值:Field字段Type类型Description描述resumeAfter
document Optional.可选的。Directs指示watch()
to attempt resuming notifications starting after the operation specified in the resume token.watch()
尝试在恢复令牌中指定的操作之后开始恢复通知。
Each change stream event document includes a resume token as the每个变更流事件文档都包括一个恢复令牌作为_id
field._id
字段。Pass the entire传递更改事件文档的整个_id
field of the change event document that represents the operation you want to resume after._id
字段,该字段表示要在之后恢复的操作。
resumeAfter
is mutually exclusive with与startAfter
andstartAtOperationTime
.startAfter
和startAtOperationTime
互斥。startAfter
document Optional.可选的。Directs指示watch()
to attempt starting a new change stream after the operation specified in the resume token.watch()
在恢复令牌中指定的操作之后尝试启动新的更改流。Allows notifications to resume after an invalidate event.允许在发生无效事件后恢复通知。
Each change stream event document includes a resume token as the每个变更流事件文档都包括一个恢复令牌作为_id
field._id
字段。Pass the entire传递更改事件文档的整个_id
field of the change event document that represents the operation you want to resume after._id
字段,该字段表示要在之后恢复的操作。
startAfter
is mutually exclusive withresumeAfter
andstartAtOperationTime
.startAfter
与resumeAfter
和startAtOperationTime
互斥。
New in version 4.2.4.2版新增。fullDocument
string Optional.可选的。By default,默认情况下,watch()
returns the delta of those fields modified by an update operation, instead of the entire updated document.watch()
返回由更新操作修改的字段的delta,而不是整个更新的文档。
Set将fullDocument
to"updateLookup"
to directwatch()
to look up the most current majority-committed version of the updated document.fullDocument
设置为"updateLookup"
以直接watch()
查找更新文档的最新多数提交版本。watch()
returns afullDocument
field with the document lookup in addition to theupdateDescription
delta.watch()
除了watch()
之外,还返回一个带有文档查找的fullDocument
字段。
Starting in MongoDB 6.0, you can set从MongoDB 6.0开始,您可以将fullDocument
to:fullDocument
设置为:"whenAvailable"
to output the document post-image, if available, after the document was inserted, replaced, or updated.以在插入、替换或更新文档后输出文档后映像(如果可用)。"required"
to output the document post-image after the document was inserted, replaced, or updated. Raises an error if the post-image is not available.以在插入、替换或更新文档后输出文档后映像。如果后映像不可用,则引发错误。
fullDocumentBeforeChange
string Optional.可选的。Starting in MongoDB 6.0, you can use the new从MongoDB 6.0开始,您可以使用新的fullDocumentBeforeChange
field and set it to:fullDocumentBeforeChange
字段,并将其设置为:"whenAvailable"
to output the document pre-image, if available, before the document was replaced, updated, or deleted.用于在文档被替换、更新或删除之前输出文档前映像(如果可用)。"required"
to output the document pre-image before the document was replaced, updated, or deleted. Raises an error if the pre-image is not available.用于在文档被替换、更新或删除之前输出文档前映像。如果前映像不可用,则引发错误。"off"
to suppress the document pre-image.以抑制文档前映像。"off"
is the default."off"
是默认设置。
batchSize
int Optional.可选的。Specifies the maximum number of change events to return in each batch of the response from the MongoDB cluster.指定在MongoDB集群的每一批响应中返回的最大更改事件数。
Has the same functionality as具有与cursor.batchSize()
.cursor.batchSize()
相同的功能。maxAwaitTimeMS
int Optional.可选的。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.1000
毫秒。collation
document Optional.可选的。Pass a collation document to specify a collation for the change stream cursor.传递排序规则文档以指定更改流游标的排序规则。
Starting in MongoDB 4.2, defaults to从MongoDB 4.2开始,如果省略,则默认为simple
binary comparison if omitted. In earlier versions, change streams opened on a single collection would inherit the collection's default collation.simple
二进制比较。在早期版本中,在单个集合上打开的更改流将继承该集合的默认排序规则。showExpandedEvents
boolean Optional.可选的。Starting in MongoDB 6.0, change streams support change notifications for DDL events, like the createIndexes and dropIndexes events.从MongoDB 6.0开始,更改流支持DDL事件的更改通知,如createIndexes
和dropIndexes
事件。To include expanded events in a change stream, create the change stream cursor using the要在变更流中包括展开的事件,请使用showExpandedEvents
option.showExpandedEvents
选项创建变更流游标。
New in version 6.0.6.0版新增。startAtOperationTime
Timestamp Optional.可选的。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.变更流的起点。如果指定的起点在过去,则它必须在oplog的时间范围内。To check the time range of the oplog, see要检查oplog的时间范围,请参阅rs.printReplicationInfo()
.rs.printReplicationInfo()
。
startAtOperationTime
is mutually exclusive with与resumeAfter
andstartAfter
.resumeAfter
和startAfter
互斥。Returns:返回值:A cursor that remains open as long as a connection to the MongoDB deployment remains open and the collection exists.只要与MongoDB部署的连接保持打开并且集合存在,游标就会保持打开状态。See Change Events for examples of change event documents.有关更改事件文档的示例,请参阅更改事件。TipSee also:另请参阅:db.watch()
and和Mongo.watch()
Availability可用性
Deployment部署
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.db.collection.watch()
。For a sharded cluster, you must issue对于分片集群,必须在db.collection.watch()
on amongos
instance.mongos
实例上发出db.collection.watch()
。
Storage Engine存储引擎
You can only use 您只能将db.collection.watch()
with the Wired Tiger storage engine.db.collection.watch()
与Wired Tiger存储引擎一起使用。
Read Concern majority
Support读取关注majority
支持
majority
SupportStarting in MongoDB 4.2, change streams are available regardless of the 从MongoDB 4.2开始,无论"majority"
read concern support; that is, read concern majority
support can be either enabled (default) or disabled to use change streams."majority"
读取关注支持如何,都可以使用更改流;也就是说,为了使用变更流,可以启用(默认)或禁用读取关注majority
支持。
In MongoDB 4.0 and earlier, change streams are available only if 在MongoDB 4.0及更早版本中,只有启用了"majority"
read concern support is enabled (default)."majority"
读取关注支持(默认),更改流才可用。
Behavior行为
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.与MongoDB部署的连接已关闭。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可恢复性
Unlike the MongoDB Drivers, 与MongoDB驱动程序不同,mongosh
does not automatically attempt to resume a change stream cursor after an error. mongosh
不会在出现错误后自动尝试恢复更改流游标。The MongoDB drivers make one attempt to automatically resume a change stream cursor after certain errors.MongoDB驱动程序尝试在出现某些错误后自动恢复更改流游标。
db.collection.watch()
uses information stored in the oplog to produce the change event description and generate a resume token associated to that operation. 使用oplog中存储的信息来生成更改事件描述,并生成与该操作相关联的恢复令牌。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.resumeAfter
或startAfter
选项的resume
令牌标识的操作已经从操作日志中删除,则db.collection.watch()
无法恢复更改流。
See Resume a Change Stream for more information on resuming a change stream.有关恢复更改流的详细信息,请参阅恢复更改流。
You cannot use在无效事件(例如,集合丢弃或重命名)关闭更改流后,不能使用resumeAfter
to resume a change stream after an invalidate event (for example, a collection drop or rename) closes the stream.resumeAfter
恢复更改流。Starting in MongoDB 4.2, you can use startAfter to start a new change stream after an invalidate event.从MongoDB 4.2开始,您可以使用startAfter
在失效事件后启动一个新的更改流。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.如果部署是分片集群,则分片移除可能会导致打开的变更流游标关闭,并且关闭的变更流游标可能无法完全恢复。
You cannot use 在无效事件(例如,集合丢弃或重命名)关闭更改流后,不能使用resumeAfter
to resume a change stream after an invalidate event (for example, a collection drop or rename) closes the stream. resumeAfter
恢复更改流。Starting in MongoDB 4.2, you can use startAfter to start a new change stream after an invalidate event.从MongoDB 4.2开始,您可以使用startAfter
在失效事件后启动一个新的更改流。
Full Document Lookup of Update Operations更新操作的完整文档查找
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. 根据更新操作期间应用的更改数量和完整文档的大小,更新操作的更改事件文档的大小可能大于16MB BSON文档限制。If this occurs, the server closes the change stream cursor and returns an error.如果发生这种情况,服务器将关闭更改流游标并返回一个错误。
Access Control访问控制
When running with access control, the user must have the 使用访问控制运行时,用户必须对集合资源具有find
and changeStream
privilege actions on the collection resource. find
和changeStream
权限操作。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.read
角色提供适当的权限。
Cursor Iteration游标迭代
MongoDB provides multiple ways to iterate on a cursor.MongoDB提供了多种对游标进行迭代的方法。
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:cursor.hasNext()
方法阻塞并等待下一个事件。要监视watchCursor
游标并迭代事件,请使用hasNext()
,如下所示:
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:cursor.tryNext()
方法是非阻塞的。要监视watchCursor
游标并迭代事件,请使用tryNext()
,如下所示:
while (!watchCursor.isClosed()) {
let next = watchCursor.tryNext()
while (next !== null) {
printjson(next);
next = watchCursor.tryNext()
}
}
Examples实例
Open a Change Stream打开变更流
The following operation opens a change stream cursor against the 以下操作打开data.sensors
collection:data.sensors
集合上的更改流游标:
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:cursor.isClosed()
方法与cursor.tryNext()
方法结合使用,以确保只有在更改流游标关闭并且最新批中没有剩余对象时,循环才会退出:
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.有关变更流输出的完整文档,请参阅变更事件。
You cannot use 不能将isExhausted()
with change streams.isExhausted()
与更改流一起使用。
Change Stream with Full Document Update Lookup使用完整文档更新查找更改流
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.fullDocument
选项设置为"updateLookup"
,以指示变更流游标查找与更新变更流事件相关联的文档的最新多数提交版本。
The following operation opens a change stream cursor against the 以下操作使用data.sensors
collection using the fullDocument : "updateLookup"
option.fullDocument : "updateLookup"
选项打开data.sensors
集合的更改流游标。
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:cursor.isClosed()
方法与cursor.tryNext()
方法结合使用,以确保只有在更改流游标关闭并且最新批中没有剩余对象时,循环才会退出:
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.fullDocument
字段中返回文档查找的结果。
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 Streams with Document Pre- and Post-Images使用文档前后映像更改流
Starting in MongoDB 6.0, you can use change stream events to output the version of a document before and after changes (the document pre- and post-images):从MongoDB 6.0开始,您可以使用更改流事件来输出更改前后文档的版本(文档前后映像):
The pre-image is the document before it was replaced, updated, or deleted.前映像是在文档被替换、更新或删除之前的文档。There is no pre-image for an inserted document.插入的文档没有前映像。The post-image is the document after it was inserted, replaced, or updated.后映像是插入、替换或更新后的文档。There is no post-image for a deleted document.已删除的文档没有后映像。Enable使用changeStreamPreAndPostImages
for a collection usingdb.createCollection()
,create
, orcollMod
.db.createCollection()
、create
或collMod
为集合启用changeStreamPreAndPostImages
。
Pre- and post-images are not available for a change stream event if the images were:如果映像为以下情况,则前映像和后映像对变更流事件不可用:
Not enabled on the collection at the time of a document update or delete operation.文档更新或删除操作时未在集合上启用。Removed after the pre- and post-image retention time set in在expireAfterSeconds
.expireAfterSeconds
中设置的前映像和后映像保留时间之后删除。The following example sets以下示例将expireAfterSeconds
to100
seconds:expireAfterSeconds
设置为100
秒:use admin
db.runCommand( {
setClusterParameter:
{ changeStreamOptions: { preAndPostImages: { expireAfterSeconds: 100 } } }
} )The following example returns the current以下示例返回当前changeStreamOptions
settings, includingexpireAfterSeconds
:changeStreamOptions
设置,包括expireAfterSeconds
:db.adminCommand( { getClusterParameter: "changeStreamOptions" } )
Setting将expireAfterSeconds
tooff
uses the default retention policy: pre- and post-images are retained until the corresponding change stream events are removed from the oplog.expireAfterSeconds
设置为off
使用默认的保留策略:保留前映像和后映像,直到从oplog中删除相应的更改流事件。If a change stream event is removed from the oplog, then the corresponding pre- and post-images are also deleted regardless of the如果更改流事件从操作日志中删除,则相应的前映像和后映像也将被删除,而不管映像前和后映像的保留时间是expireAfterSeconds
pre- and post-image retention time.expireAfterSeconds
。
Additional considerations:其他注意事项:
Enabling pre- and post-images consumes storage space and adds processing time.启用前映和后映像会消耗存储空间并增加处理时间。Only enable pre- and post-images if you need them.只有在需要时才启用前映像和后映像。Limit the change stream event size to less than 16 megabytes. To limit the event size, you can:将更改流事件大小限制为小于16兆字节。要限制事件大小,您可以:Limit the document size to 8 megabytes.将文档大小限制为8兆字节。You can request pre- and post-images simultaneously in the change stream output if other change stream event fields like如果其他变更流事件字段(如updateDescription
are not large.updateDescription
)不大,则可以在变更流输出中同时请求前映像和后映像。Request only post-images in the change stream output for documents up to 16 megabytes if other change stream event fields like如果其他更改流事件字段(如updateDescription
are not large.updateDescription
)不太大,则请求在更改流输出中为高达16兆字节的文档后映像。Request only pre-images in the change stream output for documents up to 16 megabytes if:如果出现以下情况,则仅在更改流输出中请求高达16兆字节的文档的前映像:document updates affect only a small fraction of the document structure or content, and文档更新只影响文档结构或内容的一小部分,并且do not cause a不要引起replace
change event. Areplace
event always includes the post-image.replace
更改事件。replace
事件始终包括后映像。
To request a pre-image, you set若要请求前映像,请在fullDocumentBeforeChange
torequired
orwhenAvailable
indb.collection.watch()
. To request a post-image, you setfullDocument
using the same method.db.collection.watch()
中将fullDocumentBeforeChange
设置为required
或whenAvailable
。若要请求后映像,请使用相同的方法设置fullDocument
。Pre-images are written to the前映像将写入config.system.preimages
collection.config.system.preimages
集合。Theconfig.system.preimages
collection may become large.config.system.preimages
集合可能会变大。To limit the collection size, you can set要限制集合大小,您可以为前映像设置expireAfterSeconds
time for the pre-images as shown earlier.expireAfterSeconds
时间,如前所示。Pre-images are removed asynchronously by a background process.前映像通过后台进程异步移除。
Backward-Incompatible Feature向后不兼容功能
Starting in MongoDB 6.0, if you are using document pre- and post-images for change streams, you must disable changeStreamPreAndPostImages for each collection using the 从MongoDB 6.0开始,如果您对更改流使用文档前映像和后映像,则必须使用collMod
command before you can downgrade to an earlier MongoDB version.collMod
命令为每个集合禁用changeStreamPreAndPostImages
,然后才能降级到早期的MongoDB版本。
See also: 另请参阅:
For change stream events and output, see Change Events.有关更改流事件和输出,请参阅更改事件。To watch a collection for changes, see要监视集合的更改,请参阅db.collection.watch()
.db.collection.watch()
。For complete examples with the change stream output, see Change Streams with Document Pre- and Post-Images.有关更改流输出的完整示例,请参阅文档前后映像的更改流。
Create Collection创建集合
Create a 创建已启用temperatureSensor
collection that has changeStreamPreAndPostImages enabled:changeStreamPreAndPostImages
的temperatureSensor
(温度传感器)集合:
db.createCollection(
"temperatureSensor",
{ changeStreamPreAndPostImages: { enabled: true } }
)
Populate the 用温度读数填充temperatureSensor
collection with temperature readings:temperatureSensor
集合:
db.temperatureSensor.insertMany( [
{ "_id" : 0, "reading" : 26.1 },
{ "_id" : 1, "reading" : 25.9 },
{ "_id" : 2, "reading" : 24.3 },
{ "_id" : 3, "reading" : 22.4 },
{ "_id" : 4, "reading" : 24.6 }
] )
The following sections show change stream examples for document pre- and post-images that use the 以下部分显示了使用temperatureSensor
collection.temperatureSensor
集合的文档前映像和后映像的更改流示例。
Change Stream with Document Pre-Image使用文档前映像更改流
You use the 如果可用,您可以使用完整的fullDocumentBeforeChange: "whenAvailable"
setting to output the document pre-image, if available. fullDocumentBeforeChange: "whenAvailable"
设置来输出文档前映像。The pre-image is the document before it was replaced, updated, or deleted. There is no pre-image for an inserted document.前映像是在文档被替换、更新或删除之前的文档。插入的文档没有前映像。
The following example creates a change stream cursor for the 以下示例使用temperatureSensor
collection using fullDocumentBeforeChange: "whenAvailable"
:fullDocumentBeforeChange: "whenAvailable"
为temperatureSensor
集合创建更改流游标:
watchCursorFullDocumentBeforeChange = db.temperatureSensor.watch(
[],
{ fullDocumentBeforeChange: "whenAvailable" }
)
The following example uses the cursor to check for new change stream events:以下示例使用游标检查新的变更流事件:
while ( !watchCursorFullDocumentBeforeChange.isClosed() ) {
if ( watchCursorFullDocumentBeforeChange.hasNext() ) {
printjson( watchCursorFullDocumentBeforeChange.next() );
}
}
In the example:在示例中:
Thewhile
loop runs until the cursor is closed.while
循环一直运行到游标关闭为止。如果游标有文档,hasNext()
returnstrue
if the cursor has documents.hasNext()
将返回true
。
The following example updates the 以下示例更新reading
field for a temperatureSensor
document:temperatureSensor
文档的reading
字段:
db.temperatureSensor.updateOne(
{ _id: 2 },
{ $set: { reading: 22.1 } }
)
After the temperatureSensor
document is updated, the change event outputs the document pre-image in the fullDocumentBeforeChange
field. temperatureSensor
文档更新后,更改事件会在完整的DocumentBeforeChange
字段中输出文档前映像。The pre-image contains the 前映像包含更新前的temperatureSensor
document reading
field before it was updated. temperatureSensor
文档reading
字段。For example:例如:
{
"_id" : {
"_data" : "82624B21...",
"_typeBits" : BinData(0,"QA==")
},
"operationType" : "update",
"clusterTime" : Timestamp(1649090957, 1),
"ns" : {
"db" : "test",
"coll" : "temperatureSensor"
},
"documentKey" : {
"_id" : 2
},
"updateDescription" : {
"updatedFields" : {
"reading" : 22.1
},
"removedFields" : [ ],
"truncatedArrays" : [ ]
},
"fullDocumentBeforeChange" : {
"_id" : 2,
"reading" : 24.3
}
}
See also: 另请参阅:
For document update output details, see change stream update events.有关文档更新输出的详细信息,请参阅更改流更新事件。For change stream output details, see Change Events.有关更改流输出的详细信息,请参阅更改事件。
Change Stream with Document Post-Image使用文档后映像更改流
You use the 如果可用,您可以使用fullDocument: "whenAvailable"
setting to output the document post-image, if available. The post-image is the document after it was inserted, replaced, or updated. fullDocument: "whenAvailable"
设置来输出文档后映像。后映像是插入、替换或更新后的文档。There is no post-image for a deleted document.已删除的文档没有后映像。
The following example creates a change stream cursor for the 以下示例使用temperatureSensor
collection using fullDocument: "whenAvailable"
:fullDocument: "whenAvailable"
为temperatureSensor
集合创建一个更改流游标:
watchCursorFullDocument = db.temperatureSensor.watch(
[],
{ fullDocument: "whenAvailable" }
)
The following example uses the cursor to check for new change stream events:以下示例使用游标检查新的变更流事件:
while ( !watchCursorFullDocument.isClosed() ) {
if ( watchCursorFullDocument.hasNext() ) {
printjson( watchCursorFullDocument.next() );
}
}
In the example:在示例中:
Thewhile
loop runs until the cursor is closed.while
循环一直运行到游标关闭为止。如果游标有文档,hasNext()
returnstrue
if the cursor has documents.hasNext()
将返回true
。
The following example updates the 以下示例更新reading
field for a temperatureSensor
document:temperatureSensor
文档的reading
字段:
db.temperatureSensor.updateOne(
{ _id: 1 },
{ $set: { reading: 29.5 } }
)
After the temperatureSensor
document is updated, the change event outputs the document post-image in the fullDocument
field. The post-image contains the temperatureSensor
document reading
field after it was updated. temperatureSensor
文档更新后,更改事件会在fullDocument
字段中输出文档后映像。后映像包含更新后的temperatureSensor
文档reading
字段。For example:例如:
{
"_id" : {
"_data" : "8262474D...",
"_typeBits" : BinData(0,"QA==")
},
"operationType" : "update",
"clusterTime" : Timestamp(1648840090, 1),
"fullDocument" : {
"_id" : 1,
"reading" : 29.5
},
"ns" : {
"db" : "test",
"coll" : "temperatureSensor"
},
"documentKey" : {
"_id" : 1
},
"updateDescription" : {
"updatedFields" : {
"reading" : 29.5
},
"removedFields" : [ ],
"truncatedArrays" : [ ]
}
}
See also: 另请参阅:
For document update output details, see change stream update events.有关文档更新输出的详细信息,请参阅更改流更新事件。For change stream output details, see Change Events.有关更改流输出的详细信息,请参阅更改事件。
Change Stream with Aggregation Pipeline Filter使用聚合管道筛选器更改流
Starting in MongoDB 4.2, change streams will throw an exception if the change stream aggregation pipeline modifies an event's _id field.从MongoDB 4.2开始,如果变更流聚合管道修改了事件的_id
字段,则变更流将抛出异常。
The following operation opens a change stream cursor against the 以下操作使用聚合管道打开data.sensors
collection using an aggregation pipeline to filter only insert
events:data.sensors
集合的更改流游标,以仅筛选insert
事件:
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:cursor.isClosed()
方法与cursor.hasNext()
方法结合使用,以确保只有在更改流游标关闭且最新批中没有剩余对象时,循环才会退出:
while (!watchCursor.isClosed()){
if (watchCursor.hasNext()){
printjson(watchCursor.next());
}
}
The change stream cursor only returns change events where the 更改流游标只返回operationType
is insert
. operationType
为insert
的更改事件。For complete documentation on change stream output, see Change Events.有关变更流输出的完整文档,请参阅变更事件。
Resuming a Change Stream恢复更改流
Every document returned by a change stream cursor includes a resume token as the 变更流游标返回的每个文档都包含一个resume令牌作为_id
field. _id
字段。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()
._id
文档传递给watch()
的resumeAfter
或startAfter
选项。
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.data.sensors
集合上的更改流游标。这假设生成恢复令牌的操作尚未从集群的操作日志中滚出。
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:cursor.isClosed()
方法与cursor.hasNext()
方法结合使用,以确保只有在更改流游标关闭且最新批中没有剩余对象时,循环才会退出:
while (!resumedWatchCursor.isClosed()){
if (resumedWatchCursor.hasNext()){
print(resumedWatchCursor.next());
}
}
See Resume a Change Stream for complete documentation on resuming a change stream.有关恢复更改流的完整文档,请参阅恢复更改流。