arrow_back

Building an Application with MongoDB Atlas and Natural Language API hosted on Cloud Run

Join Sign in

Building an Application with MongoDB Atlas and Natural Language API hosted on Cloud Run

1 hour 5 Credits

This lab was developed with our partner, MongoDB. Your personal information may be shared with MongoDB, the lab sponsor, if you have opted-in to receive product updates, announcements, and offers in your Account Profile.

Note: This lab requires a partner account. Please follow the lab instructions to create your account before starting the lab.

GSP1094

Google Cloud self-paced labs logo

Overview

MongoDB Atlas is MongoDB’s multi-cloud developer data platform for modern application development.

In this lab, you will build an application hosted on Cloud Run that will display a list of cakes, with the ability to view further details on the cakes, and even leave a comment! You will also learn how to leverage Atlas App Services products, such as Triggers and Functions, to call Cloud Natural Language Processing and carry out sentiment analysis on the comments.

Note : This lab is the second lab in a 2-lab series on MongoDB Atlas. Please ensure that you have completed lab 1 - Getting started with MongoDB Atlas on Google Cloud prior to starting this lab.

Objectives

In this lab, you will do the following:

  • Authenticate to Atlas App Services.
  • Query Atlas data with GraphQL.
  • Deploy an Angular application to Google Cloud Run.
  • Integrate the Google Cloud Natural Language API with Atlas App Services.

Prerequisites

Before starting this lab, you should first complete Getting Started with MongoDB Atlas on Google Cloud. This lab builds on top of the MongoDB Atlas cluster configured in that lab, and you will need the MongoDB credentials you created.

Before starting this lab, make sure you are logged into your MongoDB Atlas account.

Setup and requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources will be made available to you.

This hands-on lab lets you do the lab activities yourself in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials that you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito or private browser window to run this lab. This prevents any conflicts between your personal account and the Student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab---remember, once you start, you cannot pause a lab.
Note: If you already have your own personal Google Cloud account or project, do not use it for this lab to avoid extra charges to your account.

How to start your lab and sign in to the Google Cloud console

  1. Click the Start Lab button. If you need to pay for the lab, a pop-up opens for you to select your payment method. On the left is the Lab Details panel with the following:

    • The Open Google Cloud console button
    • Time remaining
    • The temporary credentials that you must use for this lab
    • Other information, if needed, to step through this lab
  2. Click Open Google Cloud console (or right-click and select Open Link in Incognito Window if you are running the Chrome browser).

    The lab spins up resources, and then opens another tab that shows the Sign in page.

    Tip: Arrange the tabs in separate windows, side-by-side.

    Note: If you see the Choose an account dialog, click Use Another Account.
  3. If necessary, copy the Username below and paste it into the Sign in dialog.

    {{{user_0.username | "Username"}}}

    You can also find the Username in the Lab Details panel.

  4. Click Next.

  5. Copy the Password below and paste it into the Welcome dialog.

    {{{user_0.password | "Password"}}}

    You can also find the Password in the Lab Details panel.

  6. Click Next.

    Important: You must use the credentials the lab provides you. Do not use your Google Cloud account credentials. Note: Using your own Google Cloud account for this lab may incur extra charges.
  7. Click through the subsequent pages:

    • Accept the terms and conditions.
    • Do not add recovery options or two-factor authentication (because this is a temporary account).
    • Do not sign up for free trials.

After a few moments, the Google Cloud console opens in this tab.

Note: To view a menu with a list of Google Cloud products and services, click the Navigation menu at the top-left. Navigation menu icon

Activate Cloud Shell

Cloud Shell is a virtual machine that is loaded with development tools. It offers a persistent 5GB home directory and runs on the Google Cloud. Cloud Shell provides command-line access to your Google Cloud resources.

  1. Click Activate Cloud Shell Activate Cloud Shell icon at the top of the Google Cloud console.

When you are connected, you are already authenticated, and the project is set to your Project_ID, . The output contains a line that declares the Project_ID for this session:

Your Cloud Platform project in this session is set to {{{project_0.project_id | "PROJECT_ID"}}}

gcloud is the command-line tool for Google Cloud. It comes pre-installed on Cloud Shell and supports tab-completion.

  1. (Optional) You can list the active account name with this command:
gcloud auth list
  1. Click Authorize.

Output:

ACTIVE: * ACCOUNT: {{{user_0.username | "ACCOUNT"}}} To set the active account, run: $ gcloud config set account `ACCOUNT`
  1. (Optional) You can list the project ID with this command:
gcloud config list project

Output:

[core] project = {{{project_0.project_id | "PROJECT_ID"}}} Note: For full documentation of gcloud, in Google Cloud, refer to the gcloud CLI overview guide.

Authenticate to Atlas App Services and deploy to Cloud Run

In this section, you will connect an Angular web application to Atlas App Services. The application uses the Atlas GraphQL API to display data and add documents to the Atlas database. You will also deploy the application to Cloud Run, Google Cloud’s managed compute platform.

Enable the Cloud Run and Cloud Build APIs

  1. From Cloud Shell, enable the Cloud Run and Cloud Build APIs
gcloud services enable run.googleapis.com gcloud services enable cloudbuild.googleapis.com
  1. If prompted, authorize Cloud Shell to make API calls.

  2. To see all enabled APIs, you can run:

gcloud services list

Fetch the source code

To deploy your web application, you need its source code. Use git to fetch the public Github repository.

Run the following command in Cloud Shell:

git clone https://github.com/mongodb-developer/Google-Cloud-MongoDB-Atlas-Workshop.git

Connect to App Services

Connect your web application to Atlas App Services.

  1. In Cloud Shell, click the Open Editor Open Editor icon icon. If prompted, click Open in a new window. You should see your cloned project on the left.

  2. Open the file Google-Cloud-MongoDB-Atlas-Workshop/src/environments/environment.prod.ts. You should see the following content.

export const environment = { production: true, APP_ID: '', GRAPHQL_URI: '', API_KEY: '' };

You will add your own credentials to this file. Let’s get them from Atlas App Services.

  1. Open MongoDB Atlas in a new tab in your browser and navigate to the App Services tab.

    App Services

  2. Select your application

  3. Copy your App ID and add it to the environment file.

    Copy App ID

  4. Navigate to the GraphQL section, copy the GraphQL endpoint, and add it to the environment file.

    GraphQL endpoint

  5. To generate an API key, navigate to the Authentication section.

  6. There are a set of providers available for App Services. For this application, you will use the API Keys provider. Select it from the list, and switch it on. Before generating the key, make sure to deploy the draft.

    Authentication create

  7. Generate a key, copy the value, and add it to the environment file.

  8. Finally, your environment file should look something like this:

export const environment = { production: true, APP_ID: 'bakery-lvtjx', GRAPHQL_URI: 'https://realm.mongodb.com/api/client/v2.0/app/bakery-lvtjx/graphql', API_KEY: 'RaOyilaiveCXYkNq30iHKq8LDj6kg71FvviTWJauTU5S9Il5zF0ONeDvWkNzrPQ4' };

Deploy to Cloud Run

You are ready to deploy your application! You can do that from the Cloud Shell Editor.

  1. Select Cloud Code on the left sidebar then click Cloud Run and select a project (Qwiklabs project ID).

  2. Click on the Deploy to Cloud Run icon.

    Deploy Cloud Run

  3. Enter the following configuration settings for your service:

    • Service Settings: Create a service
    • Service name: bakery-web-app
    • Deployment platform: Cloud Run (fully managed)
    • Region:
    • Authentication: Allow unauthenticated invocations

    For the Build environment, select Local.

    Finally, in the Build Settings section, select:

    • Builder: Docker
    • Docker: Google-Cloud-MongoDB-Atlas-Workshop/Dockerfile
  4. Click on the Deploy button and wait as your app is being deployed to the cloud. This can take a few minutes. Expand the process output by clicking on the Show Detailed Logs button.

  5. When the deployment is complete, you will see the URL for your application. Click on it and you will see the bakery application displaying a list of the cakes in your Atlas database.

    Cakes in application

The application uses the Atlas GraphQL API to access data from your Atlas database. Explore it by clicking on one of the cakes to open its details page. Add your comment about the cake.

Deploy Bakery web app using Cloud Run

Integrate with the Google Cloud Natural Language API

It’s now time to bring in another Google Cloud product, the Natural Language API. This will allow you to fetch the sentiment of the comments left on the cakes on your database.

Enable the Google Cloud Natural Language API

  1. The first thing to do is to enable the Natural Language API. In the console, under Marketplace search for Cloud Natural Language API and select it from the list.

  2. The API is already enabled, so click on Manage.

  3. This will take you to the Natural Language API page for your project. You will need to generate an API key to use, so select Credentials from the left-hand menu.

    Credentials

  4. Click Create Credentials at the top of the browser window and select API Key from the dropdown box to generate a key.

  5. Copy the API key that has been generated for you.

Link to App Services

Next, link the Natural Language API with Atlas App Services so you can use it from within your app.

Value

You will store some values from Google Cloud, including your new API key, inside App Services values, so they can be accessed from within multiple services, including Functions and Triggers.

  1. Select Values from the left menu under the Build heading.

    Values

  2. Click Create New Value.

  3. Enter the following details in the form that appears:

    • Give your Value a Name: gcpAPIKey
    • Choose a Type: Secret
    • Add Content: Insert your API key you copied from Google Cloud in the last section
    • Click Save
  4. Now create a second Value. Click Create New Value in the top right and add the following:

    • Give your Value a Name: gcpSentimentAnalyzeURL
    • Choose a Type: Value
    • Add Content as Custom Content with the value (including the double quotes): "https://language.googleapis.com/v1/documents:analyzeSentiment"
    • Click Save Draft
  5. By its very nature, a secret is a secret. So in order to access it, you will need to define an additional value that points to your secret that you will then call from your function later. Click Create New Value and add the following:

    • Give your Value a Name: gcpAPIKey
    • Choose a Type: Value
    • Add Content: Link to Secret
    • gcpAPIKey
    • Click Save Draft
  6. Click Review Draft & Deploy to apply the changes. Click Deploy in the modal that pops up.

Functions

Now that you have the values saved and available to reference, it’s time to write your functions that will fetch the new document and also call the Natural Language API.

  1. Select Functions from the left and click Create New Function.

  2. Enter the following details:

    • Name: analyzeCommentSentiment
    • Authentication: System
    • Leave the rest as default and click Save Draft
  3. This will open the Function Editor. Replace the default code with the following:

exports = async function(comment) { const URL = context.values.get("gcpSentimentAnalyzeURL"); const gcpAPIKey = context.values.get("gcpAPIKey"); const response = await context.http.post({ url: `${URL}?key=${gcpAPIKey}`, body: { "document": { "type": "PLAIN_TEXT", "language": "en-US", "content": comment } }, encodeBodyAsJSON: true }); // The response body is a BSON.Binary object. Parse it and return. return JSON.parse(response.body.text()); };
  1. Click Save Draft and then Review Draft & Deploy again to share your changes. Click Deploy in the modal that pops up

    This Function is fairly simple. It takes in a comment object, then assigns the values you saved earlier in Values as local variables. It then sends your comment to the Natural Language API via a POST request, parses the response to text, and returns it.

  2. Click Create New Function from inside Functions again.

  3. Enter the following details:

    • Name: getCommentAndAnalyzeSentiment
    • Authentication: System
    • Leave the rest as default and click Save Draft
  4. In the Function Editor, replace the existing code with the following:

exports = async function (changeEvent) { const commentDocument = changeEvent.fullDocument; const sentiment = await context.functions.execute("analyzeCommentSentiment", commentDocument.text); const commentsCollection = context.services.get("mongodb-atlas").db("Bakery").collection("comments"); await commentsCollection.updateOne( { _id: commentDocument._id }, { $set: { sentiment } } ); };
  1. Click Save Draft and then Review Draft & Deploy again to share your changes. Click Deploy in the modal that pops up.

This function gets the document from the changeEvent and then calls the analyzeCommentSentiment function, passing the comment text as an argument.

Now call another MongoDB Query API function, updateOne, which will update your existing document with a new sentiment field with the details you get back from the Natural Language API.

Triggers

In the last section, you set up two functions to help call out to the Natural Language API. Now create a trigger that can be called when a new comment is created, calling out to that function to request the analysis.

  1. Select Triggers from the left side.

  2. Click Add a Trigger and add the following before hitting Save:

    • Trigger Type: Database
    • Name: getCommentAndAnalyzeSentiment
    • Cluster Name: Mongo-db atlas (workshop bakery)
    • Database Name: Bakery
    • Collection Name: comments
    • Operation Type: Insert Document
    • Full Document: Enabled
    • Select An Event Type: Function
    • Function: getCommentAndAnalyzeSentiment
  3. Click Save.

  4. Click Review Draft & Deploy to deploy your changes. Click Deploy in the modal that pops up.

Testing it all together

You now have all the pieces in place.

  1. Visit the URL you were given earlier by Google Cloud when you deployed your application with Cloud Build.
    • If you haven’t got it saved, you can search for Cloud Run inside Google Cloud and it will show you your existing deployments.
  2. Click into one of your existing cakes and add a comment. You will see it added to the page under the comments section.
  3. Head back to Atlas and click Browse Collections.
  4. Click into your comments collection inside the Bakery database and have a look at the document for the comment you just wrote.
    • You will see a new field called sentiment with the Object type.
    • Expand this object, then expand the documentSentiment field (also an object). You will see the sentiment score for your comment.
Use Natural Language API's analyze sentiment on new comments

Congratulations!

In this lab, you have successfully deployed an application to Google Cloud Run, integrated it with Atlas App Services, and finally, built an automated pipeline to analyze sentiment with the Google Cloud Natural Language API.

Next Steps / Learn More

Want to keep learning MongoDB? Here are more labs to do that:

Be sure to read out the MongoDB Atlas documentation to learn more about building modern data-driven applications.

Check out MongoDB on the Google Cloud Marketplace!

Get free $500 credits for MongoDB on Google Cloud Marketplace - Applicable only for new customers

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated January 9, 2024

Lab Last Tested January 9, 2024

Copyright 2024 Google LLC All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.