MongoDB Atlas Triggers
Automate actions based on database events
⚡ What are Atlas Triggers?
Atlas Triggers automatically execute server-side logic in response to database changes or scheduled events. They help automate workflows, send notifications, and sync data without writing complex backend code.
// Database Trigger Example
exports = function(changeEvent) {
const doc = changeEvent.fullDocument;
console.log("New user created:", doc.name);
};
Output:
New user created: John Doe
Types of Triggers
Database Triggers
React to insert, update, or delete operations
// On document insert
exports = function(changeEvent) {
const newDoc = changeEvent.fullDocument;
// Process new document
};
Scheduled Triggers
Run functions at specific times or intervals
// Runs every day at midnight
exports = function() {
console.log("Daily cleanup task");
};
Authentication Triggers
Execute logic on user authentication events
// On user creation
exports = function(authEvent) {
const user = authEvent.user;
console.log("Welcome:", user.id);
};
Event Processing
Send emails, notifications, or webhooks
// Send notification
exports = function(changeEvent) {
// Send email or push notification
return { status: "sent" };
};
🔹 Creating a Database Trigger
Database triggers respond to changes in your MongoDB collections. They execute automatically when documents are inserted, updated, or deleted, enabling real-time data processing and automation.
// Trigger Configuration
{
"name": "onNewOrder",
"type": "DATABASE",
"config": {
"operation_types": ["insert"],
"database": "store",
"collection": "orders"
}
}
// Trigger Function
exports = async function(changeEvent) {
const order = changeEvent.fullDocument;
// Send confirmation email
console.log(`Order ${order._id} received`);
console.log(`Total: $${order.total}`);
// Update inventory
const mongodb = context.services.get("mongodb-atlas");
const inventory = mongodb.db("store").collection("inventory");
await inventory.updateOne(
{ _id: order.productId },
{ $inc: { stock: -order.quantity } }
);
};
Output:
Order 507f1f77bcf86cd799439011 received
Total: $49.99
🔹 Creating a Scheduled Trigger
Scheduled triggers run functions at specific times or intervals using CRON expressions. Perfect for daily reports, cleanup tasks, data synchronization, or any recurring automation needs.
// Trigger Configuration
{
"name": "dailyReport",
"type": "SCHEDULED",
"config": {
"schedule": "0 0 * * *" // Every day at midnight
}
}
// Trigger Function
exports = async function() {
const mongodb = context.services.get("mongodb-atlas");
const orders = mongodb.db("store").collection("orders");
// Get yesterday's date
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
// Count orders from yesterday
const count = await orders.countDocuments({
createdAt: { $gte: yesterday }
});
console.log(`Daily Report: ${count} orders processed`);
// Send report email or notification
return { ordersProcessed: count };
};
Output:
Daily Report: 127 orders processed
🔹 Common CRON Schedules
CRON expressions define when scheduled triggers run:
-
* * * * *- Every minute -
0 * * * *- Every hour -
0 0 * * *- Every day at midnight -
0 9 * * 1- Every Monday at 9 AM -
0 0 1 * *- First day of every month
🔹 Accessing Change Events
Change events provide detailed information about database operations. You can access the full document, operation type, and modified fields to build sophisticated automation logic.
exports = function(changeEvent) {
// Operation type: insert, update, delete, replace
const operationType = changeEvent.operationType;
// Full document (for insert/replace)
const fullDocument = changeEvent.fullDocument;
// Document ID
const documentId = changeEvent.documentKey._id;
// Updated fields (for update operations)
const updatedFields = changeEvent.updateDescription?.updatedFields;
console.log(`Operation: ${operationType}`);
console.log(`Document ID: ${documentId}`);
if (operationType === "update") {
console.log("Updated fields:", updatedFields);
}
};
🔹 Best Practices
Follow these guidelines for reliable triggers:
- Keep functions fast: Triggers should execute quickly (under 90 seconds)
- Handle errors: Use try-catch blocks to prevent failures
- Use filters: Only trigger on specific conditions to reduce executions
- Test thoroughly: Test triggers in development before production
- Monitor logs: Check trigger execution logs regularly