MongoDB Triggers ?!!

1) Equivalent to RDBMS triggers in MongoDB ?

There is no direct functionality available in MongoDB equivalent to triggers.

However, we can achieve similar results using couple of solutions:

(a) MongoDB’s “Tailable Cursors”
Tailable cursors are conceptually equivalent to the tail Unix command with the -f option (i.e. with “follow” mode).
Client can keep listening to new inserted documents based on certain criteria and take actions if any match is found.
Note that MongoDB replication uses tailable cursors to tail the primary’s oplog.
https://docs.mongodb.org/manual/tutorial/create-tailable-cursor/

We can duplicate the functionality when running in a Replica Set, however. In a Replica Set, all of the MongoDB actions are logged to an operations log (known as the oplog). The oplog is basically just a running list of the modifications made to the data. Replicas Sets function by listening to changes on this oplog and then applying the changes locally. You can create a Tailable Cursor on the opLog. Here’s an example of Trigger-like functionality .

(b) Second solution (if applicable) could be design the document schema such that there is no need for triggers and transactions in first place.
That may involve embedding of documents, arrays etc. within the same document.
Note that all updates to a document is atomic in nature.

 

  • Ask Question