MongoDB Triggers

Topics Covered

Overview

MongoDB trigger is a database operation that automatically executes in response to performing the specified event. Server-side logic execution is allowed by the database Triggers when the addition, updation, or removal operation is performed on the document. MongoDB triggers provide the Auditing, Data Consistency, Data Integrity, and Data Events features to the user.

What are Triggers in MongoDB?

MongoDB triggers are the code segments that allow server-side logic execution after the database event occurrence. Suppose when you insert, delete or update the data, then we can design complex data interactions with the help of database triggers. Triggers allow data updations after the related data changes and it also allows the new service interaction after new data insertion. For instance, after the replacement of the profile photo of the user, we can trigger the profile information update for the user. Or after the creation of a new entry, an email notification can be triggered. Following are some of the advantages provided to the users by the MongoDB triggers:

  • Auditing: You can identify the user that made particular modifications in the documents with the help of MongoDB triggers.
  • Data Consistency: MongoDB triggers can be used to check whether the data reached its defined consistent format. Let's take an example, for confirming that the name field present in the database should be in UPPERCASE.
  • Data Integrity: With the help of MongoDB triggers you can also add some conditional logic to make sure that there must be a valid combination of data in the fields of the database. For instance, for confirming that the beginning date for some specific order must be the date less than or equal to the end date for the same one.
  • Data Events: We can also add MongoDB triggers for a specific collection as an events series. For instance, we have to generate a report after the addition of some amount of data or we want to send a notification after the addition of data of a certain percentage of users.

Database Triggers in MongoDB

Server-side logic execution is allowed by the database Triggers when the addition, updation, or removal operation is performed on the document in a linked Atlas cluster of MongoDB. Data triggers in SQL execute on the database server but Database triggers in MongoDB execute on the serverless compute layer and it scales independently of the database server. Atlas functions are automatically called by the triggers and through AWS EventBridge events are forwarded to the external handlers.

Configurations

The following configuration options are provided for the MongoDB triggers:

FieldDescription
Trigger TypeIt defines the type of the trigger. For database triggers, set this value to Database.
NameDefines the trigger name.
EnabledIt is enabled by default. It's mainly used to enable or disable the trigger.
Skip Events On Re-EnableIt is disabled by default. And if it is enabled then any modification event that occurred, will not be processed when this trigger will be disabled.
Event OrderingIf this field is enabled then all the processing of trigger events will be in the same order in which they will occur. If we disabled this field then the processing of all the trigger events will be in parallel, and it seems to be faster when there is an occurrence of several events at the same time. If the event ordering is enabled, then according to the timestamps of the change events, the multiple executions of this trigger will occur sequentially. If we disabled this field then the occurrence of the multiple execution of this trigger will be independent.

The following configuration options are provided in the trigger source details section:

FieldDescription
Cluster NameIt is the name of the MongoDB service through which the trigger is associated.
Database NameThe name of the MongoDB database that has the collection.
Collection NameThat collection name is watched by the trigger for the change events.
Operation TypeCheckbox for the list of the database operations which makes the trigger to be fired. Choose the type of operation which you desire that the trigger will execute to respond to that operation.
Full DocumentIf the full document is enabled then the triggers events execution will be in an order similar to their order of occurrence. And if this field is disabled then the execution of all the trigger events will occur in parallel.

Scheduled Triggers in MongoDB

When you desire to perform some operations based on the period then the scheduled triggers come into the scenario. For instance, the generation of some reports at regular time intervals, transmitting email newsletters, etc.

Configurations

Many fields for the configuration of scheduled MongoDB triggers are the same as the MongoDB Database triggers configuration fields. The main difference between them is that the following option can be used for scheduling the trigger.

  • Schedule Type: Two mode types are provided. One type of mode is basic and the second one is advanced. Some predefined values are provided in the form of a dropdown in the basic mode for scheduling the trigger. And in the second one i.e. advance, when to fire the trigger is determined by the CRON expression.

Creating MongoDB Triggers

Step 1: On the main screen of the MongoDB Atlas, click on the ellipse option after that choose the "Load Sample Dataset".

creating mongodb triggers

Step 2: Some sample datasets will be loaded into MongoDB but this process will take some time. For the creation of a MongoDB trigger, we will use one of the datasets i.e. sample_mflix dataset.

Step 3: Now to see the loaded sample datasets, you have to click on the "Browse Collections" option.

creating mongodb triggers

Step 4: Now we desire trigger creation at the time of insertion of a new document into the collection movies of the database sample_mflix. For that, you are required to select the triggers option present at the vertical navigation bar available on the left of the display.

creating mongodb triggers

Step 5: Now for opening the trigger configuration page choose to add the trigger button.

creating mongodb triggers

Step 6: For database trigger creation click on the database.

Step 7: In the name field enter the trigger name according to your requirement.

Step 8: Trigger and data source linking will be done in the Link Data Source(s). Choose the collection, database, and cluster.

creating mongodb triggers

Step 9: Select the operation type on which you want the trigger to be fired by the operation type option.

creating mongodb triggers

Step 10: Now you have completed the settings of the trigger, now scroll down for writing a code in the function section. The code is written for updating the field last updated to the current timestamp at every new document insertion in the collection named movies. Write the code given below in the function section.

creating mongodb triggers

Function

Step 11: Now click the save button available at the bottom side of the page

Step 12: Now we click the working trigger by performing new document insertion. To go to the main page click on the "Atlas" button. After clicking the “Browse Collections”

Step 13: Now choose the database named “sample_mflix” and then select the collection named “movies”. Next, click on the “Insert Document” option.

Step 14: The document required to be inserted is shown below: creating mongodb triggers Now when you perform searching for the new inserted document using the title, then the value of the “lastupdated” field is set to the current timestamp. In this way, we can perform MongoDB triggers creation.

Trigger Functions in MongoDB

You have to keep in mind the below-given points at the time of writing a trigger:

  • A function with changeEvent is always called by the Database triggers.
  • A function without arguments must be called by the schedule triggers.
  • Function runs as a system used by the MongoDB triggers. And these functions must have full access to MongoDB data, functions, and services.
  • Suppose you want to access the MongoDB database you must connect to MongoDB using the following steps and after that, you can write operations on it.
  • Default HTTP context can also be specified by you and the perform the execution of the get request.
  • If other named functions are defined in the application, then you can call them.
  • With the help of the dependency tab, you can also add an external dependency, which enables you to define the package name and version of the external dependency.

Conclusion

  • MongoDB triggers are the code segments that allow server-side logic execution after the database event occurrence.
  • Server-side logic execution is allowed by the database Triggers when the addition, updation, or removal operation is performed on the document in a linked Atlas cluster of MongoDB.
  • Trigger Type, Name, Enabled, Skip Events On Re-Enable, and Event Ordering are the configuration options of MongoDB triggers.
  • When you desire to perform some operations based on the period then the scheduled triggers come into the scenario.