Summary摘要
updateAn当操作更新集合中的文档时,会发生updateevent occurs when an operation updates a document in a collection.update事件。
Description描述
_id |
| |
clusterTime | Timestamp |
|
collectionUUID | UUID |
|
documentKey |
| |
fullDocument |
| |
fullDocumentBeforeChange |
| |
lsid |
| |
ns |
| |
ns.coll |
| |
ns.db |
| |
operationType |
| |
updateDescription |
| |
updateDescription.disambiguatedPaths |
| |
updateDescription.removedFields |
| |
updateDescription.truncatedArrays |
| |
updateDescription.truncatedArrays.field |
| |
updateDescription.truncatedArrays.newSize |
| |
updateDescription.updatedFields |
| |
txnNumber | NumberLong |
|
wallTime | ISODate |
|
Behavior行为
Document Pre- and Post-Images文档前映像和后映像
Starting in MongoDB 6.0, you see a 从MongoDB 6.0开始,如果执行以下步骤,您将看到一个fullDocumentBeforeChange document with the fields before the document was changed (or deleted) if you perform these steps:fullDocumentBeforeChange文档,其中包含更改(或删除)文档之前的字段:
Enable the new使用changeStreamPreAndPostImagesfield for a collection usingdb.createCollection(),create, orcollMod.db.createCollection()、create或collMod为集合启用新的changeStreamPreAndPostImages字段。Set在fullDocumentBeforeChangeto"required"or"whenAvailable"indb.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以下示例将整个集群上的expireAfterSecondsto100seconds on an entire cluster:expireAfterSeconds设置为100秒:use admin
db.runCommand( {
setClusterParameter:
{ changeStreamOptions: {
preAndPostImages: { expireAfterSeconds: 100 }
} }
} )The following example returns the current以下示例返回当前changeStreamOptionssettings, includingexpireAfterSeconds:changeStreamOptions设置,包括expireAfterSeconds:db.adminCommand( { getClusterParameter: "changeStreamOptions" } )Setting将expireAfterSecondstooffuses 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如果从oplog中删除了更改流事件,则相应的预映像和后映像也将被删除,而不管映像保留时间为expireAfterSecondspre- 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 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将文档大小限制为8 MB。如果其他更改流事件字段(如updateDescriptionare not large.updateDescription)不大,您可以在更改流输出中同时请求预映像和后映像。Request only post-images in the change stream output for documents up to 16 mebibytes if other change stream event fields like如果其他更改流事件字段(如updateDescriptionare 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不要引起replacechange event. Areplaceevent always includes the post-image.replace更换事件。replace事件总是包括帖子图像。
To request a pre-image, you set要请求预映像,您可以在fullDocumentBeforeChangetorequiredorwhenAvailableindb.collection.watch(). To request a post-image, you setfullDocumentusing the same method.dbcollectionwatch()中将fullDocumentBeforeChange设置为必需或可用。要请求帖子图像,您可以使用相同的方法设置fullDocument。Pre-images are written to the预映像会写入config.system.preimagescollection.config.system.preimages集合。Theconfig.system.preimagescollection may become large. To limit the collection size, you can setexpireAfterSecondstime 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 从MongoDB 6.0开始,如果您将文档预映像和后映像用于更改流,则必须使用collMod命令为每个集合禁用collMod command before you can downgrade to an earlier MongoDB version.changeStreamPreAndPostImages,然后才能降级到早期的MongoDB版本。
Tip
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.有关更改流输出的完整示例,请参阅使用文档前后图像更改流。
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.townfield fromOxfordtoLondon, 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.towncontains a period, thedisambiguatedPathsfield shows an array with one value, to indicate thattownis not a sub-field ofhome.home.town包含一个句点,disambiguatedPaths字段显示了一个具有一个值的数组,以表示town不是home的子字段。When an update modifies a value in the当更新修改residence数组中的值以进行相同的更改时,它会生成如下所示的更新描述:residencesarray 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消除歧义的路径包括一个整数0to 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)。
update | |
replace | |
insert | 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.2的update更改事件。
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文档可能与更新操作时的文档不同。