GIANT Stories at MongoDB

How to Integrate Azure Functions with MongoDB

MongoDB Atlas, the database as a service provided by the creators of MongoDB, is available on all the major cloud providers including Microsoft Azure. In this tutorial, I’ll cover the integration of Microsoft Azure Functions with MongoDB Atlas from a developer standpoint.

Every database on the planet is a time-series database

If you can store an integer and a value you have a time-series data store. Every database on the planet can support a time-series workload so what sets MongoDB apart? A flexible document model, transactional consistency, horizontal scaling, native datetime support, real-time analytics and visualizations, and millions of users worldwide to name a few.

Working with MongoDB Stitch Through Existing Drivers – Python & PyMongo

You can now access MongoDB Stitch (and Atlas behind it) using any of the existing MongoDB Drivers – this post shows how to do it using the PyMongo Python Driver.

Connecting MongoDB Stitch to Google Places

One of the services that make available a wealth of data via API, is Google Places.

Imagine we want to provide users of our application with information about a business with whom we partner. Insurance companies do this with providers of accommodations, transportation, and healthcare. We don’t want to maintain this information, or own it - rather, we’d prefer to leverage a service that provides this information about these service providers. Google Places is just such a service provider.

For this application, we’ll use the following Stitch components to integrate MongoDB with Google Places.

Stitch Functions

Stitch functions are written in JavaScript ES6 and can be called from our SDKs, Triggers, or Webhooks and are great for coordinating data access or doing light processing alongside a query or insert. Communicating with data provider services such as Google Places is as simple as leveraging an HTTP service within a serverless stitch function:

    
const http = context.services.get("GooglePlaces");
 return http
   .get({url: GooglePlacesSearchURL})
   .then(resp=>{
       //The response body is encoded as raw BSON.Binary. Parse it to JSON.
       var search_result = EJSON.parse(resp.body.text());
    

Stitch’s Functions also let you reference context – such as services, variables, or user information – in order to make it easier to leverage services and information across your entire application. Stitch also provides several third-party services including AWS, Twilio, and Github.

Stitch Services

The HTTP service that we create here will also have an incoming webhook, meaning that it can make outgoing HTTP requests within Stitch Functions, but also handle incoming HTTP services.

Stitch Trigger

Stitch Triggers enable reactivity to inserts, updates, deletes, and replaces that occur in the database. In our case, an insert will trigger execution of a function.

Figure 1. Trigger Configuration

Building Your Application

Let’s take a look at how all the pieces of this application fit together –

Figure 2. Stitch Architectural Diagram
  1. In step 1, an application accepts input either from a user or as a result of some action the user performed (using geofencing, for example.) The input, in our case, will be the name of a business. The application will insert a document with the name of the business into MongoDB.
  2. The firing of the trigger is automatic because we configured it to watch for inserts or updates to our database.
  3. The trigger executes a custom function called getGooglePlaceInfo then captures and forwards the entire inserted document.
  4. Next, in step 4, the function we created invokes the HTTP Webhook we created. The webhook conducts the conversation between Google Places and Stitch.
  5. In step 5, Google Places will respond with a JSON document containing the requested information.

The function will catch this JSON information and update the MongoDB document. It is worth saying that the function can also manipulate the data before inserting it. Allowing it meet all your project requirements (format, types, calculations). As an example, the function may create a new GeoJSON object from the Google coordinates. All of this is done in step 6.

In Conclusion

We’ve taken a very brief look at how leveraging MongoDB Atlas, Stitch, and Triggers in conjunction with a data API service such as Google Places transforms applications into intelligent apps users will truly love to use. Because we’re adding data without having to bother the user, the application becomes much more usable, much more valuable. MongoDB Stitch and Triggers give your application the ability to react to changes in the database. Then leverage integration with external services to fetch in-context data to enrich your applications’ data further. This improves both usability and value to the user.

Without MongoDB Stitch, a developer would have had to contend with building an application server, dealing with management, availability, scalability, and backup and restoration of the data.

Oh, and did we mention that Stitch provides other benefits as well? It leverages Atlas security, adds third-party authentication and granular, field-level access controls to MongoDB data. This gives the ability for users to retrieve data anywhere. Without developers having to create REST APIs from scratch, secure and maintain them?

The content described in this blog article is publically available and can be found here: https://github.com/julienmongodb/mongodb-googleplaces

Working with MongoDB Stitch Through the mongo Shell – MongoDB Wire Protocol Support

The Stitch SDK is the best way to access MongoDB Stitch from your frontend application code – however, you may want to access Stitch from your existing tools (e.g. the mongo shell) or backend code – this post shows you how.

Building Intelligent Apps with MongoDB and Google Cloud - Part 1

Data analytics is a perpetual underachiever. Every generation of tools promises us better insight and never quite delivers. So we get stuck re-platforming and re-designing, hoping the next iteration will finally get us to the intelligence utopia. Yet modern applications must provide rich experiences, offer decision support, and continuously learn and adapt to win their users. Analytics and AI are at the heart of these Intelligent Apps.

We decided to build an Intelligent App to demonstrate how easy it is to take advantage of ML and AI cloud services without hiring a team of data scientists. First, we built a simple e-commerce application - MongoDB SwagStore - using React and MongoDB Stitch with MongoDB Atlas on GCP. Stitch saved us hundreds of lines of code and our app was ready in days. But aside from implementing stock replenishment notifications with Stitch Triggers and Twilio, it wasn’t very intelligent... yet.

We enabled our SwagStore with a product recommendation engine. Rather than implementing a recommendation engine from scratch, we used Google Cloud ML to train and tune a TensorFlow model that implements a WALS collaborative filtering algorithm. We then used Google Cloud Endpoints to serve up these personalized recommendations.

When a user authenticates, MongoDB Stitch sends an HTTP GET request to the Google Cloud Endpoint to obtain a list of recommended products.

A Stitch Function updates the recommendations array in the user document with the returned result.

exports = function() {
  //services
  const gcp = context.services.get("GoogleCloudRec");
  const mongodb = context.services.get("mongodb-atlas");
  //my swagstore collection
  const users = mongodb.db("swagstore").collection("users");
  const products = mongodb.db("swagstore").collection("products");

  return users.findOne({user_id: context.user.id})
    .then(user => {
      if(!user.gcpId) {
        return [];
      }
      //URL to GCP cloud endpoint
      const url = `https://jfmlrecengine.appspot.com/recommendation?userId=${user.gcpId}`;
      return gcp.get({ url }).then(response => { 
        console.log("Retrieved Recommendations");
        return EJSON.parse(response.body.text());
      })
      .then(result => {
        // Get the product info for the array of product ids
        return products.find({id: {"$in": result.articles}}, {_id:0, id:1, name:1, image:1}).toArray();
      })
      .then(products => {
        console.log(JSON.stringify(products));
        // Write the products to the user document
        return users.updateOne({"gcpId": user.gcpId}, { $set: { "personalized_recs" : products}})
          .then(() => { return products });
      });
    });
};

So when Jane logs into SwagStore she will see these product recommendations:

And Jasper - different ones:

By using MongoDB Stitch combined with powerful cloud services and APIs you can build a recommendation system like this very quickly and plug it right into you operational app getting your developers and data scientists to work together, operationalize insight, and deliver intelligence to your customers. Give it a try!

Stay tuned for Part 2 where SwagStore becomes even more intelligent with an AI chatbot.

MongoDB Stitch Authentication Triggers

See how Stitch authentication triggers let you use third-party user-authentication services such as Facebook or Google without losing the ability to perform custom actions when users register, sign-in, or leave.

Sending Text Messages with MongoDB Stitch & Twilio

How to send text messages from your app using MongoDB Stitch and Twilio.

Reacting to Auth Events using Stitch Triggers

MongoDB Stitch makes it easy to add authentication to your application. Several authentication providers are available to be configured using the Stitch Admin Console. Recently, authorization triggers were added to Stitch. Functions can now be executed based on authorization events such as user creation, deletion, and login.

During my Stitchcraft live coding sessions, I’ve been creating an Instagram-like application that uses Google Authentication. The Google authentication provider can be configured to return metadata with the authenticated user. I set up my provider to retrieve the user’s email, name, and profile picture. This works well as long as only the authenticated users need to see it. If you want other users to be able to access this data, you’re going to have to write it to a collection. Before authorization triggers, this could have been an arduous task.

Now it’s as simple as executing a function to perform an insert on the CREATE operation. Because I wanted to also ensure that the data in this collection stayed up-to-date, I created authorization triggers for CREATE and LOGIN and pointed them to a single upsert function as seen below.

exports = function(authEvent) {
  const mongodb = context.services.get("mongodb-atlas");
  const users = mongodb.db('data').collection('users');

  const { user, time } = authEvent;

  const newUser = {
    user_id: user.id,
    last_login: time,
    full_name: user.data.name,
    first_name: user.data.first_name,
    last_name: user.data.last_name,
    email: user.data.email,
    picture: user.data.picture
  };

  return users.updateOne({user_id: user.id}, newUser, {upsert: true});
};

During the last Stitchcraft session, I set up this authorization trigger and a database trigger that watched for changes to the full_name field. Check out the recording with the GitHub repo linked in the description. Follow me on Twitch and be notified of future Stitchcraft live coding sessions.

-Aydrian Howard
Developer Advocate
NYC
@aydrianh

Creating your first Stitch app? Start with one of the Stitch tutorials.

Want to learn more about MongoDB Stitch? Read the white paper.

Testing & Debugging MongoDB Stitch Functions

Andrew Morgan

Technical, Cloud

Testing and debugging serverless functions can be tricky – not so with MongoDB Stitch functions. This post shows how quick and easy it is through the Stitch UI.