## 1. Project Overview & Quickstart (mongodb-developer/LICENSE)

# LICENSE

Open-source repository mongodb-developer/LICENSE

### Repository Details
- **Repository:** [mongodb-developer/LICENSE](https://github.com/mongodb-developer/LICENSE)
- **Primary Language:** Code

*Note: High-volume repository documentation is actively indexed and synchronized by YakaAI.*

## 2. Official Technical Reference & Guides (mongodb-developer/mongodb-developer.github.io)

## File: README.md

# MongoDB Atlas on Google Cloud Workshop Content

This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator. It's available on http://www.atlas-google-cloud-workshop.com/.

### Installation

```
$ yarn
```

### Local Development

```
$ yarn start
```

This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.

### Build

```
$ yarn build
```

This command generates static content into the `build` directory and can be served using any static contents hosting service.

### Deployment

Using SSH:

```
$ USE_SSH=true yarn deploy
```

Not using SSH:

```
$ GIT_USER=<Your GitHub username> yarn deploy
```

### Disclaimer

Use at your own risk; not a supported MongoDB product

---

## File: docs/4-cloud-run/connect-to-app-services.mdx

---
sidebar_position: 2
---

import useBaseUrl from '@docusaurus/useBaseUrl';

# Connect to App Services

It's time to connect the web application to Atlas App Services.

1. First, open [Cloud Shell Editor](https://console.cloud.google.com/cloudshelleditor). The editor may look suspiciously like VSCode. This is because both projects use some of the same open-sourced components such as the Monaco Editor and the Language Server Protocol. You should see your cloned project on the left.

    

1. Open the **environment.prod.ts** file. You should see the following content.

    ```js title=Google-Cloud-MongoDB-Atlas-Workshop/src/environments/environment.prod.ts
    export const environment = {
      production: true,
      APP_ID: '',
      GRAPHQL_URI: '',
      API_KEY: ''
    };
    ```

    :::note
    Note that you should edit the *environment.**prod**.ts* file and not the *environment.ts* file. The first is used by Angular when building the application for production and the second — when building for development.
    :::

1. Add your own credentials to this file. You can either copy them from the open StackBlitz application or follow the instructions from [Chapter 2](/docs/app-services/app-graphql#app-services-authentication-credentials) to get them from App Services.

---

## File: docs/4-cloud-run/deploy-to-cloud-run.mdx

---
sidebar_position: 3
---

import useBaseUrl from '@docusaurus/useBaseUrl';

# Deploy to Cloud Run

Yo’re finally ready to deploy the application! You can do this from the Cloud Shell Editor.

1. Select the **Cloud Code** extension on the left sidebar.

    

1. Expand the **Cloud Run** section.

    

1. Click the Deploy to Cloud Run icon.

    

1. 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: **closest to your physical location**
    - Authentication: **Allow unauthenticated invocations**

    For the Build environment, select **Local Build**.

    Finally, in the Build Settings section, select:

    - Builder: **Docker**
    - Docker: **Google-Cloud-MongoDB-Atlas-Workshop/Dockerfile**

1. Click the **Deploy** button and wait as your app is being deployed to the cloud! This can take a few minutes. You can expand the process output by clicking on the **Show Detailed Logs** button.

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

    

    

Great job! You have just deployed a web application to a serverless cloud service!

---

## File: docs/4-cloud-run/enable-apis.mdx

---
sidebar_position: 1
---

import useBaseUrl from '@docusaurus/useBaseUrl';

# Enable Cloud APIs with Cloud Shell

:::tip
This section requires a Google Cloud account. You can create one and get $300 in free credits [here](https://cloud.google.com/free).
Alternatively, you can use this Google Cloud Skills Boost lab — [MongoDB Atlas with Natural Language API and Cloud Run](https://mdb.link/gc-lab-2). When you start the lab, you will get access to a temporary Google Cloud account that you can use for the duration of the lab.
:::

Cloud Shell is a command-line environment running Google Cloud. You will be using Cloud Shell to enable Cloud APIs you need for the application deployment.

:::info
Cloud Shell is a powerful tool that will help you greatly in your Google Cloud journey. It’s a Debian-based virtual machine, preloaded with all the tools you need for Cloud development. 
:::

## Configure Cloud Shell

1. Activate Cloud Shell by clicking on the **Activate Cloud Shell** icon.

    

1. Find your project ID in the [Cloud Console dashboard](https://console.cloud.google.com/home/dashboard).

    

1. Set your project using the `PROJECT_ID`.

    ```sh
    gcloud config set project 
    ```

## Enable the Cloud Run and Cloud Build APIs

1. From Cloud Shell, enable the Cloud Run and Cloud Build APIs

    ```sh
    gcloud services enable run.googleapis.com
    gcloud services enable cloudbuild.googleapis.com
    ```

1. If prompted, authorize Cloud Shell to make API calls.

1. You should see a success message similar to this one:

    ```sh
    Operation "operations/acf.cc11252d-30af-47ad-9d59-477a12847c9e" finished successfully.
    ```

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

    ```sh
    gcloud services list
    ```

## Fetch the source code

You need the source code of the app in order to deploy it to Cloud Run. Run `git clone` in the Cloud Shell to fetch the [public Github repository](https://github.com/mongodb-developer/Google-Cloud-MongoDB-Atlas-Workshop).

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

---

## File: docs/3-natural-language-api/configure-app-services.mdx

---
sidebar_position: 3
---

# Use the API in Atlas App Services to Analyze Sentiment

Now you want to start linking the Natural Language API with Atlas App Services so you can use it from within our app.
Before starting this section, make sure you have the Atlas App Services **Bakery** application open in your browser.

## Create a Value for the NL API URL and Key

You want to 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.

1. Click **Create New Value**.

1. 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 Value**.

1. By its very nature, a secret is a secret. So in order to access it, you need to define an additional value that points to our secret that you can then call from our function later. Click **Create a New Value** and add the following:
    - Give Your Value a Name: **gcpAPIKey**. 
    - Choose a Type: **Value**.
    - Add Content: **Link to Secret**.
    - **gcpAPIKey**.
    - Click **Save Value**.

1. You now need to create a second Value, so 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**.

1. Click **Review & Deploy Draft** to apply the changes.

## Create Atlas Functions to Analyze Sentiment

Now that you have the values saved and available to reference, it’s time to write the 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**.
1. Enter the following details:

    - Name: **analyzeCommentSentiment**.
    - Authentication: **System**.
    - Leave the rest as default and click **Save Draft**.

1. This will open the Function Editor, so replace the default code with the following:

    ```js
    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 our changes.

    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 our comment to the API via a POST request, parses the response to text, and returns it.

1. Click **Create New Function** from inside Functions again.
1. Enter the following details:
    - Name: **getCommentAndAnalyzeSentiment**.
    - Authentication: **System**.
    - Leave the rest as default and click **Save Draft**.

1. In the Function Editor, replace the existing code with the following:

    ```js
    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 }
            }
        );
    };
    ```

Hit **Save Draft** to persist your changes.

This function gets the document from the **changeEvent** and then calls the **analyzeCommentSentiment** function, passing the comment text as an argument. You then call another MongoDB Query API function, **updateOne**, which will update our existing document with a new sentiment field with the details you get back from the Natural Language API.

## Set up a Trigger to Run the Function on a New Comment

In the last section, you set up two functions to help us call out to the Natural Language API, but now you want to 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.
1. Click **Add a Trigger** and add the following before hitting **Save**:
    - Trigger Type: **Database**
    - Name: **getCommentAndAnalyzeSentiment**
    - Cluster Name: **Workshop-Bakery**
    - Database Name: **Bakery**
    - Collection Name: **comments**
    - Operation Type: **Insert**
    - Full Document: **Enabled**
    - Select An Event Type: **Function**
    - Function: **getCommentAndAnalyzeSentiment**

1. Click **Review Draft & Deploy** to deploy the changes.

## Testing it all together

Woo! You now have all the pieces in place, so it’s time to start seeing your hard work in action.

1. Go back to your StackBlitz tab which is still running the bakery application.

1. Click into one of your existing cakes and add a comment. You will see it added to the page under the **comments** section.

1. Head back to Atlas and click **Browse Collections** like you learned about in the first chapter when you inserted your first documents.

1. Click into the **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 and then expand the **documentSentiment** field (also an object), and you will see the sentiment score for your comment. Hooray!

---

## File: docs/3-natural-language-api/set-up-google-cloud.mdx

---
sidebar_position: 1
---

import useBaseUrl from '@docusaurus/useBaseUrl';

# Set up Google Cloud


:::tip
This section requires a Google Cloud account. You can create one and get $300 in free credits [here](https://cloud.google.com/free).
Alternatively, you can use this Google Cloud Skills Boost lab — [MongoDB Atlas with Natural Language API and Cloud Run](https://mdb.link/gc-lab-2). When you start the lab, you will get access to a temporary Google Cloud account that you can use for the duration of the lab.
:::


In this section, we'll be using the Google Cloud Natural Language API to analyze the sentiment of the comments left on the cakes in the web app. That's why you need to set up a Google Cloud account and project.

1. Sign in to [Cloud Console](https://console.cloud.google.com/getting-started) and create a new project.

    

    

1. Remember your project ID. The rest of the tutorial will refer to it as `PROJECT_ID`.

    

1. [Enable billing](https://console.cloud.google.com/billing) to use Google Cloud resources. If you’re a new user, you’re eligible for the [$300 Free Trial](https://cloud.google.com/free) program.

---

## File: docs/3-natural-language-api/set-up-nl-api.mdx

---
sidebar_position: 2
---

import useBaseUrl from '@docusaurus/useBaseUrl';

# Enable the Google Cloud Natural Language API

It’s now time to start bringing in another Google Cloud product, Natural Language API, that will allow us to fetch the sentiment of the comments left on the cakes in the web app.

1. The first thing you want to do is to enable the **Natural Language API**. Search for Natural Language API and select it from the list under **Marketplace**.

    

1. Click the **Enable** button so you can start using it within our project.

1. 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.

    

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

1. Copy the API key that has been generated for you. You will use it to authenticate our requests to the Natural Language API in the following section.

---

## File: docs/2-app-services/app-graphql.mdx

---
sidebar_position: 2
---

import useBaseUrl from '@docusaurus/useBaseUrl';

# Consume the API in a Web App

Data services are only practical if you use them in an actual application. Let’s do that! In this section, you will connect an Angular web application to the App Services GraphQL API you just created. 

## Run the application in StackBlitz

You will use StackBlitz, an online IDE, to run the application.

1. Open the [StackBlitz project](https://stackblitz.com/edit/mongodb-atlas-bakery?file=src/environments/environment.ts).

1. Wait until the message `Compiling application & starting dev server…` is gone. 

    

1. Fork the project so you can make changes to it.

    

In the code editor, you can see the open `environment.ts` file:

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

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

## App Services authentication credentials

1. Open [MongoDB Atlas](https://cloud.mongodb.com) in a new tab in your browser and navigate to the App Services tab.

    

1. Select the application you created in the previous section.

    

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

    

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

    

    

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

    

1. 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.

    

    

    

1. Generate a key, copy the value, and—you guessed it—add it to the environment file. 

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

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

1. Save the file and you should see a list with the cakes in your database on the right.

    

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 a cake recipe.

In the following section, you will use the Google Cloud Natural Language API to analyze the sentiment of new comments. Make sure you keep the StackBlitz tab open in your browser!

---

## File: docs/2-app-services/create-app-services-app.mdx

---
sidebar_position: 1
---

import useBaseUrl from '@docusaurus/useBaseUrl';

# Create an Atlas GraphQL API

In this section, you are going to set up with your first Atlas App Services backend, ready for using GraphQL.

## Get started with Atlas App Services

1. Start by navigating to the **App Services** tab.

    

1. You will be prompted to select a starter template. Select the **Build your own App** and click the **Next** button. 

1. The platform should automatically create your first application for you. If you have pre-existing applications in your project, you might be prompted to fill in additional configuration settings for your app. If you see the extra configuration prompt, fill in the following:
    - **Data Source**: Since you have just one cluster, Atlas has already linked it to the application.
    - **Application Name**: Give the application a meaningful name such as **Bakery**.
    - **App Deployment Model**: Make sure the deployment is set to **Single Region** and select the region closest to your physical location.

## Configure data access rules

Next, you will set up rules to control the app’s access to data.

1. At the end of the previous section, after creating your application, it will have taken you to it in your browser. On the left, under the **Data Access** heading, select **Rules**.

    

1. You will see a helper popup, explaining how **Roles** and **Filters** in App Services work. Read through it and close it. 

   

1. You need to create two rules — one for each collections.
    - Select the **cakes** collection, select the **readAll** preset, and then click **Add preset role**.
    - A popup will appear talking about **Save and Deploy**. Read it and close it.

1. Select the **comments** collection from the left, and this time, apply the **readAndWriteAll** rule. Click **Add preset role**.

1. Since you have made changes to the app by adding these rules, you need to deploy those changes. This **Review Draft & Deploy** step is on by default, to protect you from making changes unintentionally.
    - Click the **Review Draft & Deploy** button in the blue banner across the top of your screen.
    - This will show the rules you have created, as the system has added them into a new `rules.json` file. Scroll down to the bottom of the window and click **Deploy**.

## Generate a schema

GraphQL requires a strongly-typed schema. In this section, you will generate a schema for both the cakes and comments collections.

1. Click **Schema** on the left, just below where you clicked **Rules** in Step 1 of the last section.

1. Select the **cakes** collection. and click **Define a Schema**.

1. App Services will see that you already have data that it can generate a schema from, so go ahead and click **Generate schema from sampling**.

1. A JSON schema will be generated, matching the field names to their data types. At the top of the browser window, click **Save Draft** to save this new schema.

1. Scroll up to the blue banner at the top and click **Review Draft and Deploy**. Scroll through the changes and click **Deploy**.

1. Now, you will create a schema for the **comments** collection. Select **comments** from the panel on the left and then, click **Define a Schema**.

1. This time, you’ll write the schema instead of generating it. Click **or, skip and manually define your own schema**.

    

1. Delete the pre-filled content and paste the following JSON schema into the box. 

    ```json
    {
        "title": "comment",
        "properties": {
            "_id": {
                "bsonType": "objectId"
            },
            "cakeId": {
                "bsonType": "objectId"
            },
            "name": {
                "bsonType": "string"
            },
            "text": {
                "bsonType": "string"
            },
            "date": {
                "bsonType": "date"
            }
        }
    }
    ```

1. Click **Save Draft** to persist the change. Scroll up to the blue banner again and deploy the changes.

1. You now need to define a relationship between the two collections so that the comment document understands `cakeId`. Click **Add a relationship** and set it to the following before clicking **Add**:
    - Parent Field: **cakeId - objectId**
    - Linked Database: **Bakery**
    - Linked Collection: **cakes**
    - Linked Field: **_id - objectId**

:::caution
If you see the following error while adding a relationship, you might have forgotten to save your schema draft:
> You must define a schema with a valid properties object for this collection before adding a relationship.

Locate the **Save Draft** button in the top right corner of the screen and click it to persist your schema.
:::

1. Click **Save Draft** to persist the relationship you just created. Then, click **Review Draft & Deploy** and deploy the change.

## Query data with GraphQL

Now that you have the schemas in place, it’s time to run your first query to check it all works!

1. Click **GraphQL** from the left side menu, under the **Build** heading.

    

    :::info
    You see the Graph**i**QL editor (note the **i** after **Graph**). GraphiQL is an integrated development environment (IDE) for exploring GraphQL APIs.
    :::

1. Replace the comments and sample query inside the editor with the following query, which requests the name and description from the cakes collection:

    ```graphql
    query {
        cakes {
            name
            description
        }
    }
    ```

1. Click the execute button at the top to run your query, and see your cakes document returned on the right.  

    

1. Let's try a query that looks for all comments associated with a specific `cakeId`. Replace the query with the following and click the execute button again.

    ```graphql
    query {
        comments(query: {
            cakeId: {
                _id: "64759d513beb40594cb859e9"
            }
        }) {
            name
            text
            cakeId {
                name
            }
        }
    }
    ```

---

## File: docs/1-database/get-started-atlas.mdx

---
sidebar_position: 1
---

import useBaseUrl from '@docusaurus/useBaseUrl';

# Get Started with MongoDB Atlas

MongoDB Atlas is a developer data platform, integrating a multi-cloud database with a diverse set of data services. Atlas simplifies database deployment and management while enabling modern data-driven application development.

In this section, you will deploy your first MongoDB Atlas cluster.

## Register a new Atlas account

Signing up for MongoDB Atlas is completely free and doesn't require a credit card. Use the link below to create your account:

- [Try MongoDB Atlas!](https://mongodb.com/try?utm_campaign=devrel&utm_source=workshop&utm_medium=cta&utm_content=google_cloud_workshop&utm_term=stanimira.vlaeva)

## Deploy a free cluster

It's time to deploy your first cluster in MongoDB Atlas.

:::info
 You can choose from a range of cluster tiers offered by Atlas, starting from **M0** and going up to **M600**. These tiers are designed to accommodate different workload requirements and scalability needs.

For this tutorial, you will be deploying a free shared cluster from the M0 tier. You can deploy one such cluster per project. The M0 cluster is designed for small-scale development and testing purposes, offering a limited amount of storage (512 MB) and performance capacity compared to higher-tier clusters. It will allow you to explore the features and capabilities of MongoDB Atlas without incurring any costs, making it a perfect choice for a hands-on tutorial.
:::

You will deploy the cluster using the Atlas UI, so before starting, make sure you’re logged into your [account](https://cloud.mongodb.com?utm_campaign=devrel&utm_source=workshop&utm_medium=cta&utm_content=google_cloud_workshop&utm_term=stanimira.vlaeva).

1. Click the **Build a Database** button.

    

1. Select the **M0** free cluster tier.

    

1. Select a cloud provider and the region closest to your physical location. Rename your cluster to **Workshop-Bakery**.

    

1. Click **Create** to deploy your cluster.

    :::info
    Your MongoDB Atlas database deployment is inherently secure and completely locked by default. To connect, you need to establish access credentials and configure network accessibility. However, in this tutorial, you will build a serverless backend powered by Atlas App Services, which will handle the connection to your database for you. As a result, you don't need to setup direct database access.
    :::

1. Go back to your database deployment by selecting **Database** from the left-hand menu.

    

1. Creating the cluster may take a couple of minutes. Once the deployment is complete, you will see your first cluster in the list!

    

    :::note
    You have just deployed a free cluster using the Atlas UI. You can also deploy and manage Atlas deployments with the [Atlas CLI](https://www.mongodb.com/docs/atlas/cli/stable/?utm_campaign=devrel&utm_source=workshop&utm_medium=cta&utm_content=google_cloud_workshop&utm_term=stanimira.vlaeva).
    :::