MongoDB is a NoSQL Database Management System. MongoDB scales well allowing its users to store massive volumes of data. Since it’s a NoSQL database, MongoDB doesn’t group its data into relations. Instead, it groups data into Documents and Collections. This makes it possible for MongoDB users to store different types of data including unstructured data. 

When using MongoDB, you will need to ensure the integrity and consistency of your data. MongoDB provides different ways through which you can achieve this. Triggers are a good way of achieving this in MongoDB. They help MongoDB users to keep their data in check to ensure its consistency and integrity. This is good for ensuring that MongoDB users have quality data in place. In this article, we will be discussing MongoDB Triggers in detail. You will learn what they are, their types, and how to create and manage them. 

Prerequisites

  • Hands-on experience with MongoDB.

What are MongoDB Triggers?

MongoDB Triggers are a piece of code that lets you execute server-side logic after the occurrence of a database event, for example, when data is added, updated, or removed. You can use database triggers to create complex data interactions. Triggers can update information after the occurrence of related data changes or interact with services after the insertion of new data. For example, it can trigger the update of a user profile information once the user’s profile picture is replaced or trigger an email notification once a new calendar entry is made. 

MongoDB Triggers help users in the following ways:

  • Auditing: Triggers can help you to identify the user who made particular changes to a document. 
  • Data Consistency: MongoDB users can use triggers to ensure that data being entered into the database meets a defined consistent format. For example, to ensure the State field in a database is in UPPERCASE. 
  • Data Integrity: MongoDB Triggers can help you to add conditional logic to make sure that some fields have a valid combination of data. For example to ensure that Begin Date for an order record is before the End Date for the same order. 
  • Data Events: MongoDB Triggers can be added as part of a series of events to happen to a certain collection, for example, a report to be generated after a certain amount of data is added or a notification to be sent after a certain percentage of users have joined a game. 

Types of MongoDB Triggers

There are three types of MongoDB Triggers. They include the following:

  • Database Triggers: These triggers perform a particular action once a document is added, removed, or updated
  • Scheduled Triggers: These are scheduled actions that happen at a set interval or at a specific time. For example, running a clean-up process of records daily or generating a report on transaction anomalies after every minute. 
  • Authentication Triggers: These are actions that occur during the creation or deletion of users or when logging into MongoDB. They are used to perform user maintenance and user audit tracking in Realm apps. 

Simplify MongoDB ETL & Analysis Using Hevo’s No-code Data Pipeline

Hevo Data is a No-code Data Pipeline that offers a fully managed solution to set up Data Integration from 150+ Data Sources (including 40+ Free sources) and will let you directly load data from sources like MongoDB to a Data Warehouse or the Destination of your choice. It will automate your data flow in minutes without writing any line of code. Its fault-tolerant architecture makes sure that your data is secure and consistent. Hevo provides you with a truly efficient and fully automated solution to manage data in real-time and always have analysis-ready data. 

Get Started with Hevo for Free

How to Create MongoDB Triggers?

The following steps can be used to create MongoDB Triggers:

  • Step 1: Click on the Ellipse button on the main MongoDB Atlas screen. Select the “Load Sample Dataset” option. 
Loading Sample Dataset to create MongoDB Triggers
Image Source
  • Step 2: The process will take some time but it will load some sample datasets into MongoDB. We will use one of the datasets, that is, the sample_mflix dataset, to create a MongoDB trigger. 
  • Step 3: Click on the “Browse Collections” button to see the sample datasets that have been loaded. 
  • Step 4: We now want to create a trigger for when a new document is inserted into the movies collection of the sample_mflix database. Click on the “Triggers” option from the vertical navigation bar on the left. 
  • Step 5: Click on the “Add Trigger” button to open the configuration page for the trigger. 
  • Step 6: Click on “Database” to create a database trigger. 
Creating Database Trigger
Image Source
  • Step 7: Enter the name of the trigger in the “Name” field. 
  • Step 8: Select or link the trigger to a data source in the “Link Data Source(s)”. Select the Cluster, Database, and Collection. 
  • Step 9: Choose the type of operation that you want to fire the trigger under “Operation Type”.
Selecting Operation Type
Image Source

Step 10: Now that you are done with the trigger settings, scroll down the page to the “Function” section. We will write a piece of code that updates the “lastupdated” field to the current timestamp whenever a new document is added to the movies collection. Add the following code into the Function field:

exports = async function(changeEvent) {
  
  const mov= context.services.get("DevCluster").db("sample_mflix").collection("movies");
  
  try {
   await mov
    .updateOne(
      { _id: changeEvent.documentKey._id },
      { 
        $currentDate: {
        lastupdated: true
        }
      }
    );
    console.log("Field updated successfully");
    
  } catch (err) {
    
    console.error("Field update failed", err);
  }
  
  return; 
  
};
  • Step 11: Click on the “Save” button located at the bottom of the page. 
  • Step 12: We want to check whether the trigger is working by inserting a new document into the collection. Click on the “Atlas” button at the top to go back to the main page. Click the on “Browse Collections” button. 
  • Step 13: Click the “sample_mflix” database and choose the “movies” collection. Next, click “Insert Document”.
Inserting Document
Image Source
  • Step 14: Here is the document to be added:
Document Added
Image Source

When you search for the new document using its title, you will find that the “lastupdated” field for the document has been set to the current timestamp. That is how to create and use MongoDB Triggers. 

Conclusion

A MongoDB Trigger is a piece of code that allows you to run server-side logic after the occurrence of a particular event such as the addition of a new document or changes to a document. MongoDB Triggers can help you to ensure the consistency and integrity of your MongoDB data. They can also help you to know the user who made particular changes to your MongoDB data. 

As your business begins to grow, data is generated at an exponential rate across all of your company’s SaaS applications, Databases, and other sources. To meet this growing storage and computing needs of data,  you would require to invest a portion of your engineering bandwidth to Integrate data from all sources, Clean & Transform it, and finally load it to a Cloud Data Warehouse for further Business Analytics. All of these challenges can be efficiently handled by a Cloud-Based ETL tool such as Hevo Data.

Visit our Website to Explore Hevo

Hevo Data, a No-code Data Pipeline provides you with a consistent and reliable solution to manage data transfer between a variety of sources like MongoDB and a wide variety of Desired Destinations, with a few clicks. Hevo Data with its strong integration with 150+ data sources (including 40+ free sources) allows you to not only export data from your desired data sources & load it to the destination of your choice, but also transform & enrich your data to make it analysis-ready so that you can focus on your key business needs and perform insightful analysis using BI tools.

Want to take Hevo for a spin? Sign Up for a 14-day free trial and experience the feature-rich Hevo suite first hand. You can also have a look at the unbeatable pricing that will help you choose the right plan for your business needs.

Share with us your experience of learning about MongoDb Triggers in the comments below!

Nicholas Samuel
Technical Content Writer, Hevo Data

Nicholas Samuel is a technical writing specialist with a passion for data, having more than 14+ years of experience in the field. With his skills in data analysis, data visualization, and business intelligence, he has delivered over 200 blogs. In his early years as a systems software developer at Airtel Kenya, he developed applications, using Java, Android platform, and web applications with PHP. He also performed Oracle database backups, recovery operations, and performance tuning. Nicholas was also involved in projects that demanded in-depth knowledge of Unix system administration, specifically with HP-UX servers. Through his writing, he intends to share the hands-on experience he gained to make the lives of data practitioners better.