Summary
update
An
update
event occurs when an operation updates a document in a collection.Note
Disambiguation
To learn more about events that occur when collection options are modified, see the
modify
event.
Description
Field | Type | Description | |||
---|---|---|---|---|---|
| Document | A BSON object which serves as an identifier for the
change stream event. This value is used as the
The For an example of resuming a change stream by | |||
| Timestamp |
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 Events with the same To identify events for a single transaction, you can use the
combination of Changed in version 8.0. | |||
| UUID | UUID identifying the collection where the change occurred. New in version 6.0. | |||
| document | Document that contains the For sharded collections, this field also displays the full shard key
for the document. The | |||
| document | The document created or modified by a CRUD operation. This field only appears if you configured the change stream with
For more information, see Lookup Full Document for Update Operations. Changed in version 6.0. Starting in MongoDB 6.0, if you set the | |||
| document | The document before changes were applied by the operation. That is, the document pre-image. This field is available when you enable the New in version 6.0. | |||
| document | The identifier for the session associated with the transaction. Only present if the operation is part of a multi-document transaction. | |||
| document | The namespace (database and or collection) affected by the event. | |||
| string | The name of the collection where the event occurred. | |||
| string | The name of the database where the event occurred. | |||
| string | The type of operation that the change notification reports. Returns a value of | |||
| document | 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 When the Requires that you set the showExpandedEvents option to New in version 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. 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. | |||
| NumberLong | Together with the lsid, a number that helps uniquely identify a transction. Only present if the operation is part of a multi-document transaction. | |||
| The server date and time of the database operation. New in version 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:
Enable the new
changeStreamPreAndPostImages
field for a collection usingdb.createCollection()
,create
, orcollMod
.Set
fullDocumentBeforeChange
to"required"
or"whenAvailable"
indb.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
to100
seconds on an entire cluster:use admin db.runCommand( { setClusterParameter: { changeStreamOptions: { preAndPostImages: { expireAfterSeconds: 100 } } } } ) The following example returns the current
changeStreamOptions
settings, includingexpireAfterSeconds
: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.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.
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:
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 mebibytes 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 mebibytes if:
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.
To request a pre-image, you set
fullDocumentBeforeChange
torequired
orwhenAvailable
indb.collection.watch()
. To request a post-image, you setfullDocument
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 setexpireAfterSeconds
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
For change stream events and output, see Change Events.
To watch a collection for changes, see
db.collection.watch()
.For complete examples with the change stream output, see Change Streams with Document Pre- and Post-Images.
Path Disambiguation
New in version 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 fromOxford
toLondon
, 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, thedisambiguatedPaths
field shows an array with one value, to indicate thattown
is not a sub-field ofhome
.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.
Update Operations
The update
command can produce different change
events (not just update
) depending on the actual
changes it makes to the collection.
Change Event | Description |
---|---|
The update operation modified an existing document. | |
The update operation replaced the document or produced a diff that was more verbose than the original document, causing MongoDB to replace it. | |
The 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 |
Array Updates
Updates to arrays produce update
change events, but the
updateDescription.updateFields
can show different values.
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:
{ _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. The
update
change event then shows it as a change on the new
position in the array (that is, 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
.
Removal of array items with the $pull
operator
produces a change event that shows the new array:
{ _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.
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:
{ _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:
{ _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:
{ "_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.