Navigation

Database Triggers

Overview

MongoDB Stitch database triggers allow you to automatically execute Stitch functions in response to changes in your MongoDB database.

Triggers listen for changes in a specific collection using MongoDB change streams. When a trigger observes a change event that it’s configured to handle, it passes the change event to its associated Stitch function and queues the function for execution.

Configuration

You can create and manage database triggers in the Stitch UI from the Triggers page.

To create a trigger:

  1. Navigate to the Triggers page by clicking Triggers under Atlas Clusters in the left-hand navigation
  2. Click Add Database Trigger to open the trigger configuration page.
  3. Enter configuration values for the trigger and click Add Database Trigger at the bottom of the page.

You can create and manage database triggers with stitch-cli. Each trigger in an application is configured by a separate JSON file in the triggers subdirectory of the application directory.

To create a trigger:

  1. Add a configuration file to the triggers subdirectory of an application directory.
  2. Import the application directory.

Trigger configuration files have the following form:

/triggers/<trigger name>.json
{
  "type": "DATABASE",
  "name": <string>,
  "function_name": <string>,
  "config": {
    "service_name": <string>,
    "database": <string>,
    "collection": <string>,
    "operation_types": [<string>, ...],
    "full_document": <boolean>
    "match": <document>,
  },
  "disabled": <boolean>
}

Note

Stitch does not enforce specific filenames for trigger configuration files. However, once imported, Stitch will rename each configuration file to match the name of the trigger it defines.

Database Triggers have the following configuration options:

Field Description

Trigger Name

name
Required. The name of the trigger.

Linked Function

function_name
Required. The name of the Stitch function that the trigger executes whenever it fires. The trigger passes the change event that caused it to fire as the only argument to this function.

Cluster

config.service_name
Required. The name of the MongoDB Service that the trigger is associated with.

Database Name

config.database
Required. The MongoDB database that contains the watched collection.

Collection Name

config.collection
Required. The name of the collection that the trigger watches for change events.

Operation Type

config.operation_types

Required. A list of one or more change event types that cause the trigger to fire. The following change event types are valid:

  • INSERT
  • UPDATE
  • REPLACE
  • DELETE

Full Document

config.full_document

Required. If true, indicates that UPDATE change events should include the most current majority-committed version of the modified document in the fullDocument field.

Note

This option only affects UPDATE change events. INSERT and REPLACE events always include the fullDocument field. DELETE events never include the fullDocument field. For more information, see the change events reference page.

Warning

Update operations executed from MongoDB Compass or the MongoDB Atlas Data Explorer fully replace the previous document. As a result, update operations from these clients will generate REPLACE change events rather than UPDATE events.

Match Expression

config.match
Optional. A $match expression document that the trigger uses to filter change events beyond their event type. The trigger will only fire if the expression evaluates to true for a given change event.

Examples

Handle A Change Event

An online store wants to notify its customers whenever one of their orders changes location. They record each order in the store.orders collection as a document that resembles the following:

{
  _id: ObjectId("59cf1860a95168b8f685e378"),
  customerId: ObjectId("59cf17e1a95168b8f685e377")
  shipDate: ISODate("2018-06-27T16:20:42.313Z"),
  orderContents: [
    { qty: 1, name: "Earl Grey Tea Bags - 100ct" }
  ],
  shippingLocation: [
    { location: "Memphis", time: ISODate("2018-06-27T18:22:33.243Z") },
  ]
}

To automate this process, the store creates a database trigger that listens for UPDATE change events in the store.orders collection. When the trigger observes an UPDATE event, it passes the change event to its associated function, textShippingUpdate. The function checks the change event for any changes to the shippingLocation field and, if it was updated, sends a text message to the customer with the new location of the order.

../../_images/trigger-location-updater.png
Trigger Configuration
{
  "type": "DATABASE",
  "name": "shippingLocationUpdater",
  "function_name": "textShippingUpdate",
  "config": {
    "service_name": "mongodb-atlas",
    "database": "store",
    "collection": "orders",
    "operation_types": ["UDPATE"],
    "full_document": true
    "match": {},
  },
  "disabled": false
}
textShippingUpdate
exports = function (changeEvent) {
  // Destructure out fields from the change stream event object
  const { updateDescription, fullDocument } = changeEvent;

  // Check if the shippingLocation field was updated
  const updatedFields = Object.keys(updateDescription.updatedFields);
  const isNewLocation = updatedFields.some(field =>
    field.match(/shippingLocation/)
  );

  // If the location changed, text the customer the updated location.
  if (isNewLocation) {
    const { customerId, shippingLocation } = fullDocument;
    const twilio = context.services.get("twilio");
    const mongodb = context.services.get("mongodb-atlas");
    const customers = mongodb.db("store").collection("customers");

    const { location } = shippingLocation.pop();
    customers.findOne({ _id: customer_id }).then(customer => {
      twilio.send({
        to: customer.phoneNumber,
        from: context.values.get("ourPhoneNumber"),
        body: `Your order has moved! The new location is ${location}.`
      });
    });
  }
};
←   Function Utilities Values  →