EVENTGet 50% off your ticket to MongoDB.local NYC on May 2. Use code Web50! Learn more >

What are Database Triggers?

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

Database triggers can be used to implement complex data interactions. A trigger can update information when related data changes (i.e. 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 (i.e. when a new calendar entry is added, triggering an email notification).

In this article, you'll learn 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 make sure that data entered into the database is in a consistent format—for example, to make sure the City field on a database is UPPERCASE. For that, 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 make sure 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 simply 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 provides 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 three types of triggers:

  • Database Triggers: Perform some type of action when a document is updated, added, or removed.
  • Scheduled Triggers: Scheduled actions that occur at a specific time or set interval. MongoDB Atlas leverages an intuitive approach to scheduling triggers using the CRON expression language. These types of triggers can be as simple as running a daily clean-up process of temporary records, to generate a minute-by-minute report on transaction anomalies.
  • Authentication Triggers (Realm only): Actions that happen when creating or deleting a user or on login into MongoDB. These types of triggers are for performing user maintenance or user audit tracking for Realm apps.

How to Create a Trigger in MongoDB Atlas

First, we’ll start up 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 our triggers snippets for more ideas.

The steps to create your MongoDB Atlas cluster in the Cloud are:

  1. Sign up for MongoDB Atlas for free.
  2. MongoDB Atlas provides a self-explanatory wizard to create the Organization, Project, and admin user components for the initial setup.
  3. Once the initial setup is complete, it is time to build a free MongoDB cluster in a few easy steps. Start by clicking on the “Build Cluster” button and select the Free option.
  4. Then pick the Cloud Provider and Region. In this example, I am going to pick Azure Virginia-East2 (eastus2) and update the Cluster Name to be “DevCluster.” Then click “Create Cluster.” create your mongodb atlas cluster in the cloud

  5. Wait a few minutes and you will have a brand new MongoDB Atlas cluster built in the Cloud Provider and Region of your choosing.

view of new atlas cluster

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 “...” ellipse button and then select “Load Sample Dataset.” load sample dataset

  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 that will take you to the Collections tab to see the sample databases that have been created:

collections tab

  1. 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. Click on the Triggers menu option:

  1. Then click the “Add Triggers” button with the following settings:

    1. Name the database trigger anything you want. In the example below, I called it “trigMovieLastUpdated.”
    2. 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.”
    3. Make sure to select the “Insert” 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 triggers settings selections

  2. 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:

exports = async function(changeEvent) {
  
  const movies= context.services.get("DevCluster").db("sample_mflix").collection("movies");
  
  try {
   await movies
    .updateOne(
      { _id: changeEvent.documentKey._id },
      { 
        $currentDate: {
        lastupdated: true
        }
      }
    );
    console.log("Successfully updated the lastupdated field");
    
  } catch (err) {
    
    console.error("Failed to update the lastupdated field", err);
  }
  
  return; 
  
};
  1. 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.

  1. The documents in this “movies” collection have a lot of fields. For the sake of brevity to test out this trigger, we are just going to insert a few fields. The ObjectId will be auto-generated so it will look different. Then click “Insert.”

click insert

  1. After inserting the document, type the following search criteria in the Find box:

{title:"MongoDB FTW"}

add the search criteria

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

  1. The other great feature that MongoDB Atlas provides 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:

click apply

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. (See more info here: https://docs.mongodb.com/realm/reference/service-limitations/#change-streams.)

  • A database with too many triggers can cause events to slow down and generate excess latency to 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.

FAQs:

What are triggers in a database?

Code that is automatically triggered by a database operation or an event/schedule.

What are the types of triggers?

There are three types of triggers in MongoDB Atlas. One is the Database trigger used for updating data based on some action, and another is the Scheduled trigger used to execute a set of code at a specific time. On the Realm applications, there is also an Authentication trigger type used for events related to application user authentication.

Where are database triggers stored?

MongoDB database triggers are stored at the Project level of an Organization in a specific Realm application. (Atlas triggers will provision this application automatically for you.)

What is an example of a database trigger?

A trigger can be used for many use cases, like updating a Last Updated date when an edit is made on a document, recording the last Login Date on a User Profile, or making all updates to a specific field be automatically changed to UPPERCASE to provide consistency in a collection.

What is the main purpose of triggers in a database?

Triggers provide a method for a database developer to have an automated set of code that can be executed based on the incoming DML statements or other events.

How do I apply database triggers?

Database triggers are applied to a database collection or table using either the database UI or executing code. Other types of triggers are based on scheduled time or authentication events.

Does MongoDB have triggers?

Yes, MongoDB Atlas provides extensive functionality through the use of triggers. More about MongoDB triggers can be found in the documentation: https://docs.atlas.mongodb.com/triggers/.

Ready to get started?

Launch a new cluster or migrate to MongoDB Atlas with zero downtime.