I checked the document https://docs.mongodb.com/manual/reference/change-events/
I'm not sure when exactly events "replace" and "update" happen.
For example, when I use MongoDB Compass to change 1 field of a document, I expected that event "update" will fire, but when I logged the event, it's "replace".
So if an expected update is actually a "replace" event, when will the real "update" event fire?
Thanks.
In a nutshell, update
event is when you update a document without replacing it. replace
event is when you create a new document replacing the old one.
Simple example:
replset:PRIMARY> db.test.find()
{
"_id": 0,
"txt": "qwerty"
}
Doing an update
:
replset:PRIMARY> db.test.update({_id:0}, {$set:{txt:'abc'}})
results in this changestream event:
{ _id:
....
operationType: 'update',
....
Doing a save
:
replset:PRIMARY> db.test.save({_id:0, txt:'qwerty'})
results in this changestream event:
{ _id:
....
operationType: 'replace',
....
If updating a document in Compass resulted in a replace
event, that means that Compass is doing a save
operation in the background instead of an update
. This would make sense from a GUI point of view, since it's easier to save
a changed document instead of going into the trouble of checking the difference between the old document and the new one and crafting a special update
query with a specific $set
operation, which would be expensive to compute.