Change stream fullDocument on delete

I have a collection named Items with wokrspace_id (ObjectId) field on it. So whenever an item inserted/updated or deleted i want to use change stream watch method to broadcast it to users that belong to this workspace.
I have no difficulties dealing with insert/update operationTypes, i am able to access workspace_id within fullDocument prop. But it turns out to be not that straightforward to access it on delete operation.

i’ve encountered this SO issue, where @Asya_Kamsky mentioned in comments that it can be done by composing the documentKey, but unfortunately i could not accomplish this (would be grateful if there are any gists on that)

So, the question is how this can be done in most elegant way?

Hi @Ivan_Lysov,

Welcome to MongoDB community!

So there is a nice workaround I presented for Atlas triggers. Since they are based on change stream events eventually same one can be applied to your scenario.

The main Idea in the linked post is:

  1. There is a new expireField with 0 life time ttl on it.
  2. When you want to delete a document you actually set this field to current time.
  3. Your change stream event listen to an update where the expiry field is present and specify full document.
  4. The change stream will perform the needed operation and ttl will meanwhile delete that document.

To me this is the most elegant way I can think of.

Let me know if that helps



wow, thanks a lot @Pavel_Duchovny! this is an elegant solution indeed :blush:

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.