Database Manual / Change Streams / Change Events

update Event事件

Summary摘要

update

An update event occurs when an operation updates a document in a collection.当操作更新集合中的文档时,会发生update事件。

Note

Disambiguation消歧

To learn more about events that occur when collection options are modified, see the modify event.要了解有关修改集合选项时发生的事件的更多信息,请参阅modify事件。

Description描述

Field字段Type类型Description描述
_idDocument文档

A BSON object which serves as an identifier for the change stream event. This value is used as the resumeToken for the resumeAfter parameter when resuming a change stream. The _id object has the following form:BSON对象,用作更改流事件的标识符。在恢复更改流时,此值用作resumeAfter参数的resumeToken_id对象具有以下形式:

{
"_data" : <BinData|hex string>
}

The _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 or resumption. _data类型取决于MongoDB版本,在某些情况下,还取决于更改流打开或恢复时的功能兼容性版本(FCV)See Resume Tokens for the full list of _data types.有关_data类型的完整列表,请参阅恢复令牌

For an example of resuming a change stream by resumeToken, see Resume a Change Stream.有关通过resumeToken恢复更改流的示例,请参阅恢复更改流

clusterTimeTimestamp

clusterTime is the timestamp from the oplog entry associated with the event.是与事件关联的oplog条目的时间戳。

Due to oplog size limits, multi-document transactions may create multiple oplog entries. In a transaction, change stream events staged in a given oplog entry share the same clusterTime.由于oplog大小的限制多文档事务可能会创建多个oplog条目。在事务中,给定oplog条目的变更流事件共享相同的clusterTime

Events with the same clusterTime may not all relate to the same transaction. Some events don't relate to a transaction at all. Starting in MongoDB 8.0, this may be true for events on any deployment. In previous versions, this behavior was possible only for events on a sharded cluster.具有相同clusterTime的事件可能并不都与同一事务相关。有些事件根本与事务无关。从MongoDB 8.0开始,这可能适用于任何部署上的事件。在以前的版本中,这种行为仅适用于分片集群上的事件。

To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.要识别单个事务的事件,可以在更改流事件文档中使用lsidtxnNumber的组合。

Changed in version 8.0.在版本8.0中的更改。

collectionUUIDUUID

UUID identifying the collection where the change occurred.标识发生更改的集合的UUID。

New in version 6.0.在版本6.0中新增。

The collectionUUID field is only included if the change stream is created with the showExpandedEvents field set to true. For details, see showExpandedEvents.只有在创建更改流时将showExpandedEvents字段设置为true时,才会包含collectionUUID字段。有关详细信息,请参阅showExpandedEvents

documentKeydocument文档

Document that contains the _id value of the document created or modified by the CRUD operation.包含通过CRUD操作创建或修改的文档的_id值的文档。

For sharded collections, this field also displays the full shard key for the document. The _id field is not repeated if it is already a part of the shard key.对于分片集合,此字段还显示文档的完整分片键。如果_id字段已经是分片键的一部分,则不会重复。

fullDocumentdocument文档

The document created or modified by a CRUD operation.通过CRUD操作创建或修改的文档。

This field only appears if you configured the change stream with fullDocument set to updateLookup. 仅当您将更改流配置为fullDocument设置为updateLookup时,才会显示此字段。When you configure the change stream with updateLookup, the field represents the current majority-committed version of the document modified by the update operation. 当您使用updateLookup配置更改流时,该字段表示由更新操作修改的文档的当前多数提交版本。The document may differ from the changes described in updateDescription if any other majority-committed operations have modified the document between the original update operation and the full document lookup.如果任何其他多数提交的操作在原始更新操作和完整文档查找之间修改了文档,则该文档可能与updateDescription中描述的更改不同。

For more information, see Lookup Full Document for Update Operations.有关详细信息,请参阅查找更新操作的完整文档

Changed in version 6.0.在版本6.0中的更改。

Starting in MongoDB 6.0, if you set the changeStreamPreAndPostImages option using db.createCollection(), create, or collMod, then the fullDocument field shows the document after it was inserted, replaced, or updated (the document post-image). 从MongoDB 6.0开始,如果使用db.createCollection()createcollMod设置changeStreamPreAndPostImages选项,则fullDocument字段将显示插入、替换或更新后的文档(文档发布图像)。fullDocument is always included for insert events.始终包含在insert事件中。

fullDocumentBeforeChangedocument文档

The document before changes were applied by the operation. That is, the document pre-image.操作应用了更改前的文档。即文档前映像。

This field is available when you enable the changeStreamPreAndPostImages field for a collection using db.createCollection() method or the create or collMod commands.当您使用db.createCollection()方法或createcollMod命令为集合启用changeStreamPreAndPostImages字段时,此字段可用。

New in version 6.0.在版本6.0中新增。

lsiddocument文档

The identifier for the session associated with the transaction.与事务关联的会话的标识符。

Only present if the operation is part of a multi-document transaction.仅当操作是多文档事务的一部分时才存在。

nsdocument文档

The namespace (database and or collection) affected by the event.受事件影响的命名空间(数据库和/或集合)。

ns.collstring字符串

The name of the collection where the event occurred.发生事件的集合的名称。

ns.dbstring字符串

The name of the database where the event occurred.发生事件的数据库的名称。

operationTypestring字符串

The type of operation that the change notification reports.更改通知报告的操作类型。

Returns a value of update for these change events.返回这些更改事件的update值。

updateDescriptiondocument文档

A document describing the fields that were updated or removed by the update operation.描述由更新操作更新或删除的字段的文档。

updateDescription.
disambiguatedPaths
document文档

A document that provides clarification of ambiguous field descriptors in updateDescription.一份澄清updateDescription中模糊字段描述符的文档。

When the update change event describes changes on a field where the path contains a period (.) or where the path includes a non-array numeric subfield, the disambiguatedPath field provides a document with an array that lists each entry in the path to the modified field.update更改事件描述路径包含句点(.)或路径包含非数组数字子字段的字段上的更改时,消歧路径字段为文档提供一个数组,其中列出了修改字段路径中的每个条目。

Requires that you set the showExpandedEvents option to true.要求将showExpandedEvents选项设置为true

New in version 6.1.在版本6.1中新增。

updateDescription.
removedFields
array数组

An array of fields that were removed by the update operation.更新操作删除的字段数组。

updateDescription.
truncatedArrays
array数组

An array of documents which record array truncations performed with pipeline-based updates using one or more of the following stages:一组文档,记录了使用以下一个或多个阶段进行的基于管道的更新执行的数组截断:

If the entire array is replaced, the truncations will be reported under updateDescription.updatedFields.如果整个数组被替换,截断将在updateDescription.updatedFields下报告。

updateDescription.
truncatedArrays.
field
string字符串

The name of the truncated field.截断字段的名称。

updateDescription.
truncatedArrays.
newSize
integer整数

The number of elements in the truncated array.截断数组中的元素数。

updateDescription.
updatedFields
document文档

A document whose keys correspond to the fields that were modified by the update operation. The value of each field corresponds to the new value of those fields, rather than the operation that resulted in the new value.一种文档,其键对应于更新操作修改的字段。每个字段的值对应于这些字段的新值,而不是导致新值的操作。

txnNumberNumberLong

Together with the lsid, a number that helps uniquely identify a transction.lsid一起,一个有助于唯一标识事务的数字。

Only present if the operation is part of a multi-document transaction.仅当操作是多文档事务的一部分时才存在。

wallTimeISODate

The server date and time of the database operation. wallTime differs from clusterTime in that clusterTime is a timestamp taken from the oplog entry associated with the database operation event.数据库操作的服务器日期和时间。wallTimeclusterTime的不同之处在于,clusterTime是从与数据库操作事件关联的oplog条目中获取的时间戳。

New in version 6.0.在版本6.0中新增。

Behavior行为

Document Pre- and Post-Images文档前映像和后映像

Starting in MongoDB 6.0, you see a fullDocumentBeforeChange document with the fields before the document was changed (or deleted) if you perform these steps:从MongoDB 6.0开始,如果执行以下步骤,您将看到一个fullDocumentBeforeChange文档,其中包含更改(或删除)文档之前的字段:

  1. Enable the new changeStreamPreAndPostImages field for a collection using db.createCollection(), create, or collMod.使用db.createCollection()createcollMod为集合启用新的changeStreamPreAndPostImages字段。
  2. Set fullDocumentBeforeChange to "required" or "whenAvailable" in db.collection.watch().db.collection.watch()中将fullDocumentBeforeChange设置为"required""whenAvailable"

Example fullDocumentBeforeChange document in the change stream output:更改流输出中的示例fullDocumentBeforeChange文档:

"fullDocumentBeforeChange" : {
"_id" : ObjectId("599af247bb69cd89961c986d"),
"userName" : "alice123",
"name" : "Alice Smith"
}

For complete examples with the change stream output, see Change Streams with Document Pre- and Post-Images.有关更改流输出的完整示例,请参阅使用文档前后图像更改流

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 to 100 seconds on an entire cluster:以下示例将整个集群上的expireAfterSeconds设置为100秒:

      use admin
      db.runCommand( {
      setClusterParameter:
      { changeStreamOptions: {
      preAndPostImages: { expireAfterSeconds: 100 }
      } }
      } )
    • The following example returns the current changeStreamOptions settings, including expireAfterSeconds:以下示例返回当前changeStreamOptions设置,包括expireAfterSeconds

      db.adminCommand( { getClusterParameter: "changeStreamOptions" } )
    • Setting expireAfterSeconds to off 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.如果从oplog中删除了更改流事件,则相应的预映像和后映像也将被删除,而不管映像保留时间为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 mebibytes. To limit the event size, you can:将更改流事件大小限制为小于16兆字节。要限制事件大小,您可以:

    • Limit the document size to 8 megabytes. You can request pre- and post-images simultaneously in the change stream output if other change stream event fields like updateDescription are not large.将文档大小限制为8 MB。如果其他更改流事件字段(如updateDescription)不大,您可以在更改流输出中同时请求预映像和后映像。
    • Request only post-images in the change stream output for documents up to 16 mebibytes 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 mebibytes if:在以下情况下,仅在更改流输出中请求最多16兆字节的文档的预图像:

      • document updates affect only a small fraction of the document structure or content, and文档更新仅影响文档结构或内容的一小部分,以及
      • do not cause a replace change event. A replace event always includes the post-image.不要引起replace更换事件。replace事件总是包括帖子图像。
  • To request a pre-image, you set fullDocumentBeforeChange to required or whenAvailable in db.collection.watch(). To request a post-image, you set fullDocument using the same method.要请求预映像,您可以在dbcollectionwatch()中将fullDocumentBeforeChange设置为必需或可用。要请求帖子图像,您可以使用相同的方法设置fullDocument。
  • Pre-images are written to the config.system.preimages collection.预映像会写入config.system.preimages集合。

    • The config.system.preimages collection may become large. To limit the collection size, you can set expireAfterSeconds time for the pre-images as shown earlier.config.system.preimages集合可能会变大。要限制集合大小,您可以为预映像设置expireAfterSeconds时间,如前所示。
    • Pre-images are removed asynchronously by a background process.预图像由后台进程异步删除。

Important

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 collMod command before you can downgrade to an earlier MongoDB version.从MongoDB 6.0开始,如果您将文档预映像和后映像用于更改流,则必须使用collMod命令为每个集合禁用changeStreamPreAndPostImages,然后才能降级到早期的MongoDB版本。

Tip

Path Disambiguation路径消歧

New in version 6.1.在版本6.1中新增。

The updateDescription field notes changes made to specific fields in documents by an operation. These field descriptors use dots (.) as path separators and numbers as array indexes, which leads to some ambiguity when it contains field names that use dots or numbers.updateDescription字段记录了操作对文档中特定字段所做的更改。这些字段描述符使用点(.)作为路径分隔符,使用数字作为数组索引,当它包含使用点或数字的字段名时,会导致一些歧义。

When an update event reports changes involving ambiguous fields, the disambiguatedPaths document provides the path key with an array listing each path component.update事件报告涉及模糊字段的更改时,disambiguatedPaths(消歧路径)文档为路径键提供了一个数组,其中列出了每个路径组件。

Note

The disambiguatedPaths field is only available on change streams started with the showExpandedEvents optiondisambiguatedPaths字段仅在以showExpandedEvents选项开头的更改流上可用

For example, consider a document that lists people and the towns in which they live:例如,考虑一份列出人们及其居住城镇的文档:

{
"name": "Anthony Trollope",
"home.town": "Oxford",
"residences": [
{"0": "Oxford"},
{"1": "Sunbury"}
]
}
  • When an update modifies the home.town field from Oxford to London, it produces an update description that looks like this:当更新将home.town字段从Oxford修改为London时,它会生成一个如下所示的更新描述:

    "updateDescription": {
    "updatedFields": {
    "home.town": "London"
    },
    "disambiguatedPaths": {
    "home.town": [ "home.town" ]
    }
    }

    Because the field home.town contains a period, the disambiguatedPaths field shows an array with one value, to indicate that town is not a sub-field of home.因为字段home.town包含一个句点,disambiguatedPaths字段显示了一个具有一个值的数组,以表示town不是home的子字段。

  • When an update modifies a value in the residences array to make the same change, it produces an update description that looks like this:当更新修改residence数组中的值以进行相同的更改时,它会生成如下所示的更新描述:

    "updateDescription": {
    "updatedFields": {
    "residences.0.0": "London"
    },
    "disambiguatedPaths": { "residences.0.0": [ "residences", 0, "0" ] }
    }

    The disambiguated paths include an integer 0 to indicate the array index and the string "0" to indicate the field name within the nested document.消除歧义的路径包括一个整数0表示数组索引,字符串"0"表示嵌套文档中的字段名。

There are two cases where disambiguatedPath does not include a numeric field:有两种情况下disambiguatedPath不包括数字字段:

  • When the first field in the path is a numeric string (i.e. 0.name). This is not ambiguous since the first field cannot be an array index.当路径中的第一个字段是数字字符串(即0.name)时。这并不含糊,因为第一个字段不能是数组索引。
  • When the numeric string field has leading zeroes (i.e., 0001). This is not ambiguous since an integer cannot have leading zeroes.当数字字符串字段有前导零(即0001)时。这并不含糊,因为整数不能有前导零。

Update Operations更新操作

The update command can produce different change events (not just update) depending on the actual changes it makes to the collection.update命令可以根据它对集合所做的实际更改产生不同的更改事件(而不仅仅是update)。

Change Event更改事件Description描述
updateThe update operation modified an existing document.更新操作修改了现有文档。
replaceThe update operation replaced the document or produced a diff that was more verbose than the original document, causing MongoDB to replace it.更新操作替换了文档或产生了比原始文档更详细的差异,导致MongoDB替换它。
insertThe update operation attempted to update a document that doesn't exist and instead added the document to the collection. This only occurs when the update runs with the upsert option enabled.更新操作试图更新一个不存在的文档,而是将该文档添加到集合中。仅当更新在启用upsert选项的情况下运行时才会发生这种情况。

Array Updates数组更新

Updates to arrays produce update change events, but the updateDescription.updateFields can show different values.对数组的更新会产生更新update事件,但updateDescription.updateFields可以显示不同的值。

For example, consider the following document and updates:例如,考虑以下文档和更新:

db.students.insertOne( { student_id: 1, scores: [ ] } )

db.students.updateOne(
{ student_id: 1 },
{ $push: { scores: 0.85 } }
)

db.students.updateOne(
{ student_id: 1 },
{ $push: { scores: 0.94 } }
)

db.students.updateOne(
{ student_id: 1 },
{ $pull: { scores: 0.94 } }
)

The first update operates on an empty array. Here, the $push produces an update change event where the field is replaced by single-entry array with the given value:第一次更新对空数组进行操作。在这里,$push生成一个update更改事件,其中字段被具有给定值的单条目数组替换:

{
_id: { _data: '82642AD66B000000012B022C0100296E5A10045DC4B11BEA5F4319A8E7CAF46816ED71461E5F6964002B060004' },
operationType: 'update',
clusterTime: Timestamp({ t: 1680529003, i: 1 }),
ns: { db: 'communication_chat', coll: 'students' },
documentKey: { student_id: 1 },
updateDescription: {
updatedFields: { scores: [ 0.85 ] },
removedFields: [],
truncatedArrays: []
}
}

In the second update operation, the array now contains values. 在第二次更新操作中,数组现在包含值。The $push adds a new entry in the array. $push在数组中添加了一个新条目。The update change event then shows it as a change on the new position in the array (that is, scores.1):然后,update更改事件将其显示为数组中新位置的更改(即scores.1):

{
_id: { _data: '82642AD673000000012B022C0100296E5A10045DC4B11BEA5F4319A8E7CAF46816ED71461E5F6964002B060004' },
operationType: 'update',
clusterTime: Timestamp({ t: 1680529011, i: 1 }),
ns: { db: 'communication_chat', coll: 'students' },
documentKey: { student_id: 1 },
updateDescription: {
updatedFields: { 'scores.1': 0.94 },
removedFields: [],
truncatedArrays: []
}
}

If you run the update operation again to add a third score to the student's record, it would produce an update change event that modifies scores.2.如果你再次运行更新操作,将第三个分数添加到学生的记录中,它将产生一个修改scores.2update更改事件。

Removal of array items with the $pull operator produces a change event that shows the new array:使用$pull运算符删除数组项会产生一个显示新数组的更改事件:

{
_id: { _data: '82642AD673000000012B022C0100296E5A10045DC4B11BEA5F4319A8E7CAF46816ED71461E5F6964002B060004' },
operationType: 'update',
clusterTime: Timestamp({ t: 1680529011, i: 1 }),
ns: { db: 'communication_chat', coll: 'students' },
documentKey: { student_id: 1 },
updateDescription: {
updatedFields: { scores: [ 0.85 ] },
removedFields: [],
truncatedArrays: []
}
}

Array Truncation数组截断

Update operations that reduce the number of elements in arrays through the pipeline updates, such as with the $addFields or $set aggregation stages, show the updated array and new size in the truncatedArrays field.通过管道更新减少数组中元素数量的更新操作,例如使用$addFields$set聚合阶段,在truncatedArrays(截断的数组)字段中显示更新的数组和新的大小。

db.students.insertOne( { student_id: 2, scores: [ 0.85, 0.94, 0.78 ] } )

db.students.updateOne(
{ student_id: 2 },
[ { $addFields: { scores: [ 0.85, 0.94 ] } } ]
)

db.students.updateOne(
{ student_id: 2 },
[ { $addFields: { scores: [ 0.85, 0.94, 0.78 ] } } ]
)

The change event from the first update, which used the $addFields stage to remove a value from the scores field shows the change in the truncatedArrays field:第一次更新的更改事件(使用$addFields阶段从分数字段中删除一个值)显示了truncatedArrays字段的更改:

{
_id: { _data: '82642AD673000000012B022C0100296E5A10045DC4B11BEA5F4319A8E7CAF46816ED71461E5F6964002B060004' },
operationType: 'update',
clusterTime: Timestamp({ t: 1680529011, i: 1 }),
ns: { db: 'communication_chat', coll: 'students' },
documentKey: { student_id: 2 },
updateDescription: {
updatedFields: {},
removedFields: [],
truncatedArrays: [ { fields: "scores", newSize: 2 } ]
}
}

The change event from the second update, which used the $addFields stage to add a value back to the scores field, shows the update in the updatedFields field:第二次更新的更改事件使用$addFields阶段将值添加回scores字段,在updatedFields字段中显示了更新:

{
_id: { _data: '82642AD673000000012B022C0100296E5A10045DC4B11BEA5F4319A8E7CAF46816ED71461E5F6964002B060004' },
operationType: 'update',
clusterTime: Timestamp({ t: 1680529011, i: 1 }),
ns: { db: 'communication_chat', coll: 'students' },
documentKey: { student_id: 2 },
updateDescription: {
updatedFields: { scores.2: 0.78 },
removedFields: [],
truncatedArrays: []
}
}

Example示例

The following example illustrates an update event:以下示例说明了update事件:

{
"_id": { <Resume Token> },
"operationType": "update",
"clusterTime": <Timestamp>,
"wallTime": <ISODate>,
"ns": {
"db": "engineering",
"coll": "users"
},
"documentKey": {
"_id": ObjectId("58a4eb4a30c75625e00d2820")
},
"updateDescription": {
"updatedFields": {
"email": "alice@10gen.com"
},
"removedFields": ["phoneNumber"],
"truncatedArrays": [ {
"field" : "vacation_time",
"newSize" : 36
} ]
}
}

The following example illustrates an update event for change streams opened with the fullDocument : updateLookup option:以下示例说明了使用fullDocument : updateLookup选项打开的更改流的update事件:

{
"_id": { <Resume Token> },
"operationType": "update",
"clusterTime": <Timestamp>,
"wallTime": <ISODate>,
"ns": {
"db": "engineering",
"coll": "users"
},
"documentKey": {
"_id": ObjectId("58a4eb4a30c75625e00d2820")
},
"updateDescription": {
"updatedFields": {
"email": "alice@10gen.com"
},
"removedFields": ["phoneNumber"],
"truncatedArrays": [ {
"field" : "vacation_time",
"newSize" : 36
} ],
"disambiguatedPaths": { }
},
"fullDocument": {
"_id": ObjectId("58a4eb4a30c75625e00d2820"),
"name": "Alice",
"userName": "alice123",
"email": "alice@10gen.com",
"team": "replication"
}
}

The fullDocument document represents the most current majority-committed version of the updated document. fullDocument文档代表更新文档的最新多数提交版本。The fullDocument document may vary from the document at the time of the update operation depending on the number of interleaving majority-committed operations that occur between the update operation and the document lookup.根据更新操作和文档查找之间发生的交错多数提交操作的数量,fullDocument文档可能与更新操作时的文档不同。