BlogRun AI wherever your compliance framework demands. Read blog >
BlogRetrieval accuracy is now a competitive advantage Read blog >

What are Database Triggers?

A database trigger is code that executes server-side logic when a database event occurs, such as when data is added, updated, replaced, or removed.

Get Started Free
Learn more about Atlas

Database triggers can be used to implement complex data interactions. A trigger can update information when related data changes (e.g., when a user profile picture is replaced, triggering an update of the user activity information) or interact with a service when new data is inserted (e.g., when a new calendar entry is added, triggering an email notification).

This article will teach the following:

What Are the Main Purposes of Triggers in a Database?

There are many reasons to use triggers in a database:

  • Audit: To add fields in the database that capture who made a change on a record. For example, a compliance team has the business requirement of recording who updated any of the records. Using triggers to record that information in a Last Updated User field would meet that requirement.
  • Data Consistency: To ensure that data entered into the database is in a consistent format—for example, to ensure that the City field on a database is in UPPERCASE — a trigger can be created to perform that function, ensuring the data is consistent, independent of the format of the incoming City field.
  • Data Integrity: To add conditional logic, to ensure that a set of fields has a valid combination of data, for example, to ensure the order record’s Begin Date is before an order record’s End Date. Using a trigger can help ensure that happens before a transaction has been committed.
  • Data Events: To add a trigger as part of a complex series of events happening in a collection—for example, a report generated after a set of data added or a notification sent back to users when enough participants have joined a given game.

Database Triggers in MongoDB Atlas

MongoDB Atlas supports database triggers that let the user program the function that will be executed when the database event is fired, take care of server management, and provide a handy user interface (which means less code to write). Atlas also offers additional types of triggers that support the complex requirements of modern applications.

Per the documentation, triggers are available for MongoDB Atlas clusters running MongoDB version 3.6 or later.

Types of Database Triggers

MongoDB provides two types of triggers:

How to Create a Trigger in MongoDB Atlas

First, we’ll start with a free MongoDB Atlas account and then populate the database with sample data.

Then we’ll build out a use case using database DDL triggers. That will update the “lastupdated” field on an insert of a new document in the “sample_mflix.movies” collection (which is part of the sample datasets provided by MongoDB).

This is a simple example to showcase how easy it is to set up a trigger. However, there are endless possibilities for trigger usage to cover your specific use case. Please see MongoDB’s triggers snippets for more ideas.

The steps to create a cluster in MongoDB Atlas are:

  1. Sign up for MongoDB Atlas for free.

  2. MongoDB Atlas provides a self-explanatory wizard to create the initial setup's organization, project, and admin user components.

  3. Once the initial setup is complete, it’s time to build a free MongoDB cluster in a few easy steps. Click on the “Build Cluster” button and select the Free option.

    Deploy your cluster UI

  4. Then, select the Cloud Provider and Region. In this example, I will select AWS Virginia-East2 (eastus2) and update the Cluster Name to “DevCluster.” Then, click “Create Cluster.”

    Deploy your cluster UI second image.

  5. Wait a few minutes, and a new MongoDB Atlas cluster will be built in the cloud provider and region of your choosing.

DevCluster overview.

Now that we have a free MongoDB Atlas cluster built, we can add some sample data to the cluster following these easy steps:

  1. In the main MongoDB Atlas screen, click the “Load sample data.” button and then select “Load Sample Dataset.”

    DevCluster overview, loading sample data.

  2. This will take a few minutes, but it will populate your MongoDB Atlas with some sample datasets that we will use to build out the database trigger use case.

  3. Click on the “Collections” button, which will take you to the Collections tab to see the sample database that has been created:

Data UI

Now that our sample data is created, let’s create a simple database trigger as part of our use case for when a new document gets inserted into the “sample_mflix.movies” collection.

  1. On the left side navigation, click on the Triggers menu option.

  2. Then select the data source(s) and deployment region where you would like to enable a trigger. The example uses “DevCluster” as the data source and “AWS Virginia-East2 (eastus2)” as the deployment region. Next, click the “Get Started” button.

    Create a Trigger page UI.png
  3. Choose or link a new cluster on the “Link Data Source(es),” and pick your database and relevant collection—in this case, “sample_mflix” and “movies.”

  4. Make sure to select the “Insert Document” Operation Type. Think of the “Operation Type” as what will fire the trigger, whether it be the INSERT, UPDATE, DELETE, or REPLACE DML statements.

    Add Trigger UI.png
  5. Name the database trigger anything you want. In the example below, I called it “trigMovieLastUpdated.”

    Add a Trigger UI Part 2.png
    Add a Trigger UI Part 3.png
  6. Once you have completed the trigger settings, scroll down to the Function section and use the following code to update the “lastupdated” field with the current timestamp when a new document is inserted into the movies collection:

7. Click “Save” at the bottom of the page.

We have defined a database trigger. Next, we will insert a new document into the “movies” collection to test and make sure the trigger is working.

  1. Go back to the main screen of the cluster and click on the “Collections” tab. Then navigate to the “sample_mflix” database and “movies” collection. After, click the “Insert Document” button.
    Collections Tab UI.png
  2. The documents in this “movies” collection have a lot of fields. To test out this trigger for brevity, we will just insert a few fields. The ObjectId will be auto-generated so that it will look different. Then click “Insert.”
    Insert Document UI.png
  3. After inserting the document, type the following search criteria in the Find box: {title:"Learn More About MongoDB"}
    Search_for_Document_.png

You will see the new document inserted with the “lastupdated” field populated with the current timestamp.

  1. Another great feature of MongoDB Atlas is that you can instantly see the trigger execution and log without having to dig through metadata database entries.
  2. Go back to your Triggers section on the left-side navigation bar and click the Logs tab. Then, click the “Apply” button to refresh the trigger logs. This will quickly show you the name of the trigger executed, Status, Time Taken, and any console output from the trigger:
Database triggers final screenshot

Summary

  • Triggers are an excellent method to provide automated functionality to a database. But don't overuse them, as they can add pressure to your MongoDB cluster, since triggers are based on change streams.
  • A database with too many triggers can cause events to slow down and generate excess latency in your operations.
  • Designing triggers based on business requirements prevents business logic from creeping into your application code, making your data higher-quality and more consistent.

FAQ

Get started with Atlas today

Get started in seconds. Our free clusters come with 512 MB of storage so you can play around with sample data and get oriented with our platform.
Try FreeContact sales
GET STARTED WITH:
  • 125+ regions worldwide
  • Sample data sets
  • Always-on authentication
  • End-to-end encryption
  • Command line tools