MongoDB Atlas Triggers let you run code in response to events happening in your MongoDB database.
Imagine you’re building an e-commerce site. When a new order comes in, you want to do a few things: send a confirmation email, update inventory, and maybe notify a shipping service. Instead of building a separate service to constantly poll your orders collection for new entries, you can use Atlas Triggers. When a document is inserted into the orders collection, an Atlas Trigger can automatically execute a piece of serverless JavaScript code (a "function") to handle these downstream actions.
Here’s a simplified look at how it works. Let’s say you have a collection named products and you want to automatically update a last_sold_at timestamp whenever a product is added to an order.
First, you’d define a trigger in your Atlas project. This trigger would be configured to listen for Insert operations on the orders collection.
{
"name": "UpdateLastSoldTimestamp",
"database": "ecommerce",
"collection": "orders",
"event_type": "INSERT",
"full_document": true,
"function_name": "updateProductTimestamp"
}
Next, you’d write the associated Atlas Function. This is a serverless JavaScript function that Atlas runs for you.
exports = async function(changeEvent) {
const order = changeEvent.fullDocument; // The new order document
const products = context.services.get("mongodb-atlas").db("ecommerce").collection("products");
if (order && order.items && order.items.length > 0) {
for (const item of order.items) {
await products.updateOne(
{ _id: item.productId },
{ $set: { last_sold_at: new Date() } }
);
console.log(`Updated last_sold_at for product ID: ${item.productId}`);
}
}
return true; // Indicate success
};
When a new order document like this is inserted:
{
"_id": ObjectId("65a8c1b3f1d7a4b1c8e9f0a1"),
"userId": "user123",
"items": [
{ "productId": ObjectId("65a8c1b3f1d7a4b1c8e9f0a2"), "quantity": 1 },
{ "productId": ObjectId("65a8c1b3f1d7a4b1c8e9f0a3"), "quantity": 2 }
],
"totalAmount": 150.00,
"createdAt": ISODate("2024-01-18T10:00:00.000Z")
}
The UpdateLastSoldTimestamp trigger fires. It captures the changeEvent, extracts the fullDocument (the new order), and then executes the updateProductTimestamp function. This function iterates through the items in the order and updates the last_sold_at field in the corresponding products documents.
Atlas Triggers are powerful because they decouple your application logic. The order service just needs to insert an order document. It doesn’t need to know about inventory management or timestamp updates. Atlas handles that automatically. You can also configure triggers for UPDATE and DELETE events, and even schedule triggers to run at specific times.
The underlying mechanism uses MongoDB’s Change Streams. When a qualifying change occurs in a collection, Atlas publishes an event. This event is picked up by the Atlas Triggers service, which then invokes the configured function, passing the change event data as an argument. The functions themselves run on Atlas Functions, a serverless compute platform, meaning you don’t manage servers for this logic.
A common point of confusion is how to access other MongoDB collections or services within a trigger function. You use the context.services object. For example, context.services.get("mongodb-atlas").db("your_db_name").collection("your_collection_name") gives you a handle to a MongoDB collection. You can also integrate with other Atlas services like Twilio for SMS or SendGrid for email through pre-built integrations or custom HTTP requests.
You can also chain triggers. For instance, an UPDATE trigger on the products collection that sets last_sold_at could itself trigger another function to send a low-stock alert if the quantity drops below a certain threshold.
The next logical step is to explore Scheduled Triggers, which allow you to run functions at recurring intervals, independent of database changes.