Database Trigger

I am having three collections in a single database.I want to do insert operation in the first collection with the condition in my second collection that the values should be within particular limits and then only it will be inserted otherwise the values that fails this condition should be inserted in the third collection.can any one give a solution


MongoDB does not support database triggers. The best way to handle it should be in the application itself where you can have more validations and that gives you more control.

However, you may use transactions to perform the operation, so when you are beginning to insert, you can start the transaction, and then add your validations and then redirect the query to database2 or database 3 and then end the transaction.
That way, you will be sure it does not get lost in between.



In addition to transactions, there’s Stitch Triggers which I believe is still in its infancy. I had a quick play with it at one of MongoDB’s World events last year.

However, based on the little you’ve mentioned, I’m suspecting a potential schema redesign. Perhaps you can give a more concrete example?.

1 Like

I have implemented some kind of triggers using the Change Streams feature

I have an external process, using the change streams API that modifies some other collections based on the incoming changes. It is not as safe as a real trigger cause nothing ensures your external process is alive when the triggering operations happen but it fulfilled my needs.

At startup of my external process, I make sure that I did not missed any triggering operations and it becomes quite safe this way.

1 Like

Good shout! Forgot about Change Streams.

Thank You all…!!!Really it was very helpful,I will work it out and send the feedback.

can I know how to create a function and insert values according to it using mongodb.
I am really stuck with it can you please help me.

Change streams is covered in course M040.

There is an introduction at

1 Like

Thanks @steevej-1495 @007_jb for directing to Change Streams, I completely agree that this is the best way to have triggers functionality in the database.

@PRIYADARSHNNI_51855 the link @steevej-1495 shared has a section called Examples, it includes very thorough steps on how to get started. Let me know if you need any additional help and sorry for the delay in my response.


There is a lot of good stuff in this discussion.

In summary, change streams are a good replacement for triggers in MongoDB.
As for the original requirement of keeping consistency between 2 documents from @PRIYADARSHNNI_51855, using a transaction would preserve the data integrity need.