1. Project Overview & Quickstart (mongodb-developer/LICENSE)
LICENSE
Open-source repository mongodb-developer/LICENSE
Repository Details
- Repository: 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, a modern static website generator. It's available on http://www.atlas-google-cloud-workshop.com/.
Installation
$ yarnLocal Development
$ yarn startThis 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 buildThis 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 deployNot using SSH:
$ GIT_USER=<Your GitHub username> yarn deployDisclaimer
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.
First, open Cloud Shell Editor. 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.
Open the environment.prod.ts file. You should see the following content.
js title=google-cloud-mongodb-atlas-workshop/src/environments/environment.prod.tsexport 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.
:::Add your own credentials to this file. You can either copy them from the open StackBlitz application or follow the instructions from Chapter 2 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.
Select the Cloud Code extension on the left sidebar.
Expand the Cloud Run section.
Click the Deploy to Cloud Run icon.
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
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.
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.
Alternatively, you can use this Google Cloud Skills Boost lab β MongoDB Atlas with Natural Language API and Cloud Run. 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
Activate Cloud Shell by clicking on the Activate Cloud Shell icon.
Find your project ID in the Cloud Console dashboard.
Set your project using the
PROJECT_ID.shgcloud config set project
Enable the Cloud Run and Cloud Build APIs
From Cloud Shell, enable the Cloud Run and Cloud Build APIs
shgcloud services enable run.googleapis.com gcloud services enable cloudbuild.googleapis.comIf prompted, authorize Cloud Shell to make API calls.
You should see a success message similar to this one:
shOperation "operations/acf.cc11252d-30af-47ad-9d59-477a12847c9e" finished successfully.To see all enabled APIs, you can run:
shgcloud 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.
git clone https://github.com/mongodb-developer/Google-Cloud-MongoDB-Atlas-Workshop.gitFile: 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.
Select Values from the left menu under the Build heading.
Click Create New Value.
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.
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.
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.
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.
Select Functions from the left and click Create New Function.
Enter the following details:
- Name: analyzeCommentSentiment.
- Authentication: System.
- Leave the rest as default and click Save Draft.
This will open the Function Editor, so replace the default code with the following:
jsexports = 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()); };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.
Click Create New Function from inside Functions again.
Enter the following details:
- Name: getCommentAndAnalyzeSentiment.
- Authentication: System.
- Leave the rest as default and click Save Draft.
In the Function Editor, replace the existing code with the following:
jsexports = 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.
Select Triggers from the left side.
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
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.
Go back to your StackBlitz tab which is still running the bakery application.
Click into one of your existing cakes and add a comment. You will see it added to the page under the comments section.
Head back to Atlas and click Browse Collections like you learned about in the first chapter when you inserted your first documents.
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.
Alternatively, you can use this Google Cloud Skills Boost lab β MongoDB Atlas with Natural Language API and Cloud Run. 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.
Sign in to Cloud Console and create a new project.
Remember your project ID. The rest of the tutorial will refer to it as
PROJECT_ID.Enable billing to use Google Cloud resources. If youβre a new user, youβre eligible for the $300 Free Trial 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.
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.
Click the Enable button so you can start using it within our project.
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.
Click Create Credentials at the top of the browser window and select API Key from the dropdown box to generate a key.
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.
Open the StackBlitz project.
Wait until the message
Compiling application & starting dev serverβ¦is gone.Fork the project so you can make changes to it.
In the code editor, you can see the open environment.ts file:
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
Open MongoDB Atlas in a new tab in your browser and navigate to the App Services tab.
Select the application you created in the previous section.
Copy your App ID and add it to the environment file.
Navigate to the GraphQL section, copy the GraphQL endpoint, and add it to the environment file.
To generate an API key, navigate to the Authentication section.
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.
Generate a key, copy the value, andβyou guessed itβadd it to the environment file.
Finally, your environment file should look something like this:
tsexport 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' };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
Start by navigating to the App Services tab.
You will be prompted to select a starter template. Select the Build your own App and click the Next button.
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.
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.
You will see a helper popup, explaining how Roles and Filters in App Services work. Read through it and close it.
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.
Select the comments collection from the left, and this time, apply the readAndWriteAll rule. Click Add preset role.
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.jsonfile. 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.
Click Schema on the left, just below where you clicked Rules in Step 1 of the last section.
Select the cakes collection. and click Define a Schema.
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.
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.
Scroll up to the blue banner at the top and click Review Draft and Deploy. Scroll through the changes and click Deploy.
Now, you will create a schema for the comments collection. Select comments from the panel on the left and then, click Define a Schema.
This time, youβll write the schema instead of generating it. Click or, skip and manually define your own schema.
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" } } }Click Save Draft to persist the change. Scroll up to the blue banner again and deploy the changes.
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.
:::
- 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!
Click GraphQL from the left side menu, under the Build heading.
:::info
You see the GraphiQL editor (note the i after Graph). GraphiQL is an integrated development environment (IDE) for exploring GraphQL APIs.
:::Replace the comments and sample query inside the editor with the following query, which requests the name and description from the cakes collection:
graphqlquery { cakes { name description } }Click the execute button at the top to run your query, and see your cakes document returned on the right.
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.graphqlquery { 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:
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.
Click the Build a Database button.
Select the M0 free cluster tier.
Select a cloud provider and the region closest to your physical location. Rename your cluster to Workshop-Bakery.
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.
:::Go back to your database deployment by selecting Database from the left-hand menu.
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.
:::