Atlas triggers help you run code automatically when something happens in your database. This makes your app smarter and faster without extra work.
0
0
Atlas triggers overview in MongoDB
Introduction
Send a welcome email when a new user signs up.
Update related data when a record changes.
Clean up old data automatically at set times.
Notify your team when important changes happen.
Syntax
MongoDB
Triggers are set up in the Atlas UI or via API. You define: - When the trigger runs (event or schedule) - What database and collection it watches - The function (JavaScript) it runs
Triggers use JavaScript functions to run your code.
You can choose between database event triggers or scheduled triggers.
Examples
This runs when a new document is inserted and logs the user's name.
MongoDB
// Example of a database trigger function exports = function(changeEvent) { const doc = changeEvent.fullDocument; console.log(`New user: ${doc.name}`); };
This runs on a schedule you set, like every day at midnight.
MongoDB
// Example of a scheduled trigger function exports = function() { console.log('Running cleanup task'); // Add cleanup code here };
Sample Program
This function runs when a new user document is inserted. It returns a message with the user's name and email.
MongoDB
// This is a database trigger function example exports = function(changeEvent) { const doc = changeEvent.fullDocument; return { message: `User ${doc.name} added with email ${doc.email}` }; };
OutputSuccess
Important Notes
Atlas triggers run in the cloud, so you don't need your app server to be always on.
Make sure your trigger functions are efficient to avoid slowing down your database.
You can test triggers in the Atlas UI before using them live.
Summary
Atlas triggers automate actions based on database events or schedules.
They use JavaScript functions to define what happens.
Triggers help keep your app responsive and reduce manual work.