4

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.

0xh8h
  • 3,271
  • 4
  • 34
  • 55
  • An `"update"` using the update modifiers such as `$set`, etc to only modify parts of the document you specify under those modifiers. A "replace" is an operation which does not use any of those modifiers. Actually you are meant to be using the API of `updateOne()` and `replaceOne()` as either explicitly prohibits usage without or with the modifiers respectively. If you think you mean something else, then please show an example with code and result documents. No screenshots please. Everything is all represented with text. – Neil Lunn Mar 25 '19 at 07:48

1 Answers1

5

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.

kevinadi
  • 13,365
  • 3
  • 33
  • 49