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:
There are many reasons to use triggers in a database:
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.
MongoDB provides three types of triggers:
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:
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.”
Wait a few minutes and you will have a brand new MongoDB Atlas cluster built in the Cloud Provider and Region of your choosing.
Now that we have a free MongoDB Atlas cluster built, we can add some sample data to the cluster following these easy steps:
In the main MongoDB Atlas screen, click the “...” ellipse button and then select “Load Sample Dataset.”
Then click the “Add Triggers” button with the following settings:
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;
};
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.
{title:"MongoDB FTW"}
You will see the new document inserted with the “lastupdated” field populated with the current timestamp.
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.
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.)
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.
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.