Docs HomeMongoDB Manual

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描述
_idDocumentA 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:
{
"_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. See Resume Tokens for the full list of _data types.
For an example of resuming a change stream by resumeToken, see Resume a Change Stream.
clusterTimeTimestampThe timestamp from the oplog entry associated with the event.
Change stream event notifications associated with a multi-document transaction all have the same clusterTime value: the time when the transaction was committed.
On sharded clusters, events with the same clusterTime may not all relate to the same transaction. Some events don't relate to a transaction at all.有些事件根本与事务无关。
To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
New in version 4.0. 4.0版新增。
collectionUUIDUUIDUUID identifying the collection where the change occurred.
New in version 6.0. 6.0版新增。
documentKeydocumentDocument that contains the _id value of the document created or modified by the CRUD operation.
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.
fullDocumentdocumentThe document created or modified by a CRUD operation.
This field only appears if you configured the change stream with fullDocument set to 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. 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.
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). fullDocument is always included for insert events.
fullDocumentBeforeChangedocumentThe 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.
New in version 6.0. 6.0版新增。
lsiddocumentThe identifier for the session associated with the transaction.与事务关联的会话的标识符。
Only present if the operation is part of a multi-document transaction.
New in version 4.0. 4.0版新增。
nsdocumentThe namespace (database and or collection) affected by the event.
ns.collstringThe name of the collection where the event occurred.
ns.dbstringThe name of the database where the event occurred.
operationTypestringThe type of operation that the change notification reports.
Returns a value of update for these change events.
updateDescriptiondocumentA document describing the fields that were updated or removed by the update operation.
updateDescription.
disambiguatedPaths
documentA document that provides clarification of ambiguous field descriptors in 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.
Requires that you set the showExpandedEvents option to true.
New in version 6.1. 6.1版新增。
updateDescription.
removedFields
arrayAn array of fields that were removed by the update operation.
updateDescription.
truncatedArrays
arrayAn array of documents which record array truncations performed with pipeline-based updates using one or more of the following stages:
Note
If the entire array is replaced, the truncations will be reported under updateDescription.updatedFields.
updateDescription.
truncatedArrays.
field
stringThe name of the truncated field.
updateDescription.
truncatedArrays.
newSize
integerThe number of elements in the truncated array.
updateDescription.
updatedFields
documentA 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.
txnNumberNumberLongTogether with the lsid, a number that helps uniquely identify a transction.
Only present if the operation is part of a multi-document transaction.
New in version 4.0. 4.0版新增。
wallTimeISODateThe 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.
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:

  1. Enable the new changeStreamPreAndPostImages field for a collection using db.createCollection(), create, or collMod.
  2. Set fullDocumentBeforeChange to "required" or "whenAvailable" in db.collection.watch().

Example fullDocumentBeforeChange document in the change stream output:

"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.

    • The following example sets expireAfterSeconds to 100 seconds:

      use admin
      db.runCommand( {
      setClusterParameter:
      { changeStreamOptions: { preAndPostImages: { expireAfterSeconds: 100 } } }
      } )
    • The following example returns the current changeStreamOptions settings, including 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.
    • 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. You can request pre- and post-images simultaneously in the change stream output if other change stream event fields like updateDescription are not large.
    • 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.
    • Request only pre-images in the change stream output for documents up to 16 megabytes if:

      • 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.
  • 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.
  • Pre-images are written to the config.system.preimages collection.

    • 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.
    • 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.

Tip

See also: 另请参阅:

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.

When an update event reports changes involving ambiguous fields, the disambiguatedPaths document provides the path key with an array listing each path component.

Note

The disambiguatedPaths field is only available on change streams started with the showExpandedEvents option

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:

    "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.

  • When an update modifies a value in the residences array to make the same change, it produces an update description that looks like this:

    "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.

There are two cases where disambiguatedPath does not include a numeric field:

  • 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.
  • When the numeric string field has leading zeroes (i.e., 0001). This is not ambiguous since an integer cannot have leading zeroes.

Example实例

The following example illustrates an update event:

{
"_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:

{
"_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. 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.