MongoDB Stitch Functions – The AWS re:Invent Stitch Rover Demo

This is the fourth in a series of blog posts examining how the MongoDB Mobile/Stitch-controlled rover was put together for our re:Invent demo. This post focuses on how a Stitch Function is used to provide aggregated sensor data such as the average temperature for the last 5 minutes.

A common question we were asked at re:Invent is how Stitch’s serverless Functions compare with AWS Lambda functions. Stitch functions are designed to be very light-weight (run as Goroutines and deliver low latency – ideal, for example, when working with a database (especially as your function has a persistent MongoDB connection). In contrast, Lambda functions are more heavy-weight (Lambda spins up containers to run your functions in) – better suited to compute-heavy operations.

You write your functions in JavaScript (ES6) through the Stitch UI or the command line. We created this function (getReadings) to fetch a rover’s sensor data for the specified interval and then return the computed average, minimum, and maximum values:

exports = function(roverId, start, end){
  const mdb = context.services.get('mongodb-atlas');
  const sensors = mdb.db("Rovers").collection("Sensors");

  return sensors.find({"id": roverId, "time":{"$gt":start,"$lt":end}})
    .toArray()
    .then(readings => {
     let data = objArray.map(readings => readings.reading);
     return {"Average": data.reduce((a,b) => a + b, 0) / data.length,
        "Min": Math.min(...readings),
        "Max": Math.max(...readings)};
  });
};

This function can then be called from your app frontend code:

Calling a MongoDB Stitch Function from a client frontend

The frontend code to run this function is as simple as this:

context.functions.execute("getReadings", myId, samplePeriod.start, 
    samplePeriod.end);

There’s a lot more that you can do in functions, such as sending data to another cloud service. You’ll see an example of this in the next post which shows how a Stitch Trigger calls a Stitch function to send MongoDB Atlas data to AWS Kinesis.

If you can’t wait then you can find all of the code in the Stitch Rover GitHub repo.





Leave a Reply

Your email address will not be published. Required fields are marked *