Skip to main content

Setting up a Document Database

with Amazon DocumentDB (with MongoDB compatibility) and AWS Cloud9

Introduction

Overview

Amazon DocumentDB (with MongoDB compatibility) is a fast, scalable, highly available, and fully managed document database service that supports MongoDB workloads, and makes it easy to store, query, and index JSON data.

This tutorial shows you how to get started with Amazon DocumentDB using AWS Cloud9. You will learn how to connect to your Amazon DocumentDB cluster from your AWS Cloud9 environment with a mongo shell and run a few queries.

For new DocumentDB customers, this walkthrough should not cost anything.

Implementation

LOREM IPSUM

Intermediate

10 minutes

Amazon DocumentDB and AWS Cloud9 are free-tier eligible. See AWS Cloud9 pricing and Amazon DocumentDB pricing for more information. 

For new users, this walkthrough should be free.

May 8, 2020

Architecture

This diagram shows the final architecture of this walkthrough.

Diagram showing the architecture of security groups for Amazon DocumentDB and AWS Cloud9 within a VPC, illustrating client access and security group relationships in an AWS Region.

Create an AWS Cloud9 Environment

1. Create the environment

Using the AWS management console, on the AWS Cloud9 management console, choose Create environment.

Screenshot of the AWS Cloud9 interface showing the option to create a new environment, featuring the text 'A cloud IDE for writing, running, and debugging code' and a highlighted 'Create environment' button.

2. Name the environment

Enter the name DocumentDBCloud9.

Choose Next step.

Screenshot of the 'Name environment' step in the AWS Cloud9 environment creation process, showing the environment name set as 'DocumentDBCloud9' and options to add a description or proceed to the next step.

Create a security group

1. Configure the security group

On the Amazon EC2 management console, under Network & Security, choose Security groups.

Choose Create security group.

  • For Security group name, enter demoDocDB.

  • For Description, enter a description.

  • For VPC, accept the usage of your default VPC

2. Add an inbound rule

In the Inbound rules section, choose Add rule.

For Type, choose Custom TCP Rule.

For Port Range, enter 27017.

The source security group is the security group for the AWS Cloud9 environment you just created. Keep the Source as the default value of Custom and enter "cloud9" in the field adjacent to Custom to see a list of available security groups.

Screenshot of the AWS console showing how to configure an inbound security group rule for a VPC, allowing custom TCP traffic on port 27017, typically used for Amazon DocumentDB, with Cloud9 as the selected security group.

3. Select the security group

Choose the security group with the name aws-cloud9-<environment name>.

Accept all other defaults and choose Create security group. You do not need to modify the outbound rules.

This screenshot shows you the security groups that were created in this step as well as the AWS Cloud9 security group that was created when you created an AWS Cloud9 environment.

Screenshot showing the AWS Security Groups list in the AWS Cloud9 interface, displaying security groups related to an Amazon DocumentDB setup. Includes group IDs, names, VPC IDs, descriptions, and ownership details.

Create an Amazon DocumentDB cluster

1. Create a cluster

On the Amazon DocumentDB management console, under Clusters, choose Create.

Screenshot showing the instance class selection menu during the creation of an Amazon DocumentDB cluster in the AWS console, including various compute and memory options for instance types.

2. Configure the cluster

On the Create Amazon DocumentDB cluster page, select db.t3.medium under Instance class, and then choose 1 for Number of instances.

These options will help minimize costs.

Leave other settings at their default.

Screenshot showing the instance class selection menu during the creation of an Amazon DocumentDB cluster in the AWS console, including various compute and memory options for instance types.

3. Create credentials

In the Authentication section, enter a username and password.

Screenshot showing the authentication setup screen for Amazon DocumentDB in AWS Cloud9. It displays the fields for entering the master username and password, along with relevant password requirements and information links.

4. Show advanced settings

Turn on Show advanced settings.

Screenshot of the AWS DocumentDB Cloud9 interface showing the 'Show advanced settings' toggle, 'Cancel' link, and the highlighted 'Create cluster' button.

5. Select the security group

In the Network settings section, for VPC security groups, choose demoDocDB.

Choose Create cluster.

Amazon DocumentDB is now provisioning your cluster, which can take up to a few minutes to finish. You can connect to your cluster when both the cluster and instance status show as Available. While Amazon DocumentDB provisions the cluster, complete the remaining steps to connect to your Amazon DocumentDB cluster.

Screenshot showing the selection of VPC security groups, with 'demoDocDB (VPC)' and 'default (VPC)' groups selected, in the AWS Console. This is used to control inbound and outbound traffic for AWS resources such as DocDB and Cloud9.

Install the mongo shell

1. Open IDE

If necessary, open the AWS Cloud9 management console, navigate to Your environments, and choose DocumentDBCloud9.

Choose open IDE.

2. Create the repository file

At the command prompt, create the repository file with the following code:

echo -e "[mongodb-org-3.6] \nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/amazon/2013.03/mongodb-org/3.6/x86_64/\ngpgcheck=1 \nenabled=1 \ngpgkey=https://www.mongodb.org/static/pgp/server-3.6.asc" | sudo tee /etc/yum.repos.d/mongodb-org-3.6.repo

3. Install the shell

When it is complete, install the mongo shell with the following code:

sudo yum install -y mongodb-org-shell

4. (Optional) Encrypt data in transit

To encrypt data in transit, download the CA certificate for Amazon DocumentDB.

You are now ready to connect to your Amazon DocumentDB cluster.

Connect to your Amazon DocumentDB Cluster

1. Select your cluster

On the Amazon DocumentDB management console, under Clusters, locate your cluster. This post uses the cluster docdb-2020-02-08-14-15-11.

Choose the cluster you created by clicking on the cluster identifier (i.e., docdb-2020-02-08-14-15-11 in this example).

Screenshot of the Amazon DocumentDB cluster list view in the AWS Management Console, showing details such as cluster identifier, engine version, status, instances, and maintenance.

2. Copy the connection string

Copy the connection string provided under “Connect to this cluster with the mongo shell”

Omit <insertYourPassword> so that you are prompted for the password by the mongo shell when you connect. This way, you don’t have to type your password in cleartext.

Screenshot showing an example command to connect to an Amazon DocumentDB cluster using the mongo shell with SSL parameters and user credentials.

3. Connect to the cluster

Your connection string should look like the following code (see screenshot).

When you enter your password and can see the rs0:PRIMARY> prompt, you are successfully connected to your Amazon DocumentDB cluster.

For information about troubleshooting, see Troubleshooting Amazon DocumentDB.

Screenshot of an AWS Cloud9 terminal showing a command to connect to a MongoDB instance using the mongo shell with SSL and authentication options.

Insert and query data

Now that you are connected to your cluster, you can run a few queries to get familiar with using a document database.

1. Insert a single document

To insert a single document, enter the following code:

db.collection.insert({"hello":"DocumentDB"})

You get the following output:

WriteResult({ "nInserted" : 1 })

2. Read the document

You can read the document that you wrote with the findOne() command (because it only returns a single document). See the following code:

db.collection.findOne()

You get the following output:

{ "_id" : ObjectId("5e401fe56056fda7321fbd67"), "hello" : "DocumentDB" }

3. Perform more queries

To perform a few more queries, consider a gaming profiles use case. First, insert a few entries into a collection entitled profiles. See the following code:

db.profiles.insertMany([{ "_id" : 1, "name" : "Tim", "status": "active", "level": 12, "score":202},{ "_id" : 2, "name" : "Justin", "status": "inactive", "level": 2, "score":9},{ "_id" : 3, "name" : "Beth", "status": "active", "level": 7, "score":87},{ "_id" : 4, "name" : "Jesse", "status": "active", "level": 3, "score":27}])

You get the following output:

{ "acknowledged" : true, "insertedIds" : [ 1, 2, 3, 4 ] }

4. Return all documents in the profiles section

Use the find() command to return all the documents in the profiles collection. See the following code:

db.profiles.find()

You get the following output:

{ "_id" : 1, "name" : "Tim", "status" : "active", "level" : 12, "score" : 202 }{ "_id" : 2, "name" : "Justin", "status" : "inactive", "level" : 2, "score" : 9 }{ "_id" : 3, "name" : "Beth", "status" : "active", "level" : 7, "score" : 87 }{ "_id" : 4, "name" : "Jesse", "status" : "active", "level" : 3, "score" : 27 }

5. Query for a single document

Use a query for a single document using a filter. See the following code.

db.profiles.find({name: "Jesse"})

You get the following output:

{ "_id" : 4, "name" : "Jesse", "status" : "active", "level" : 3, "score" : 27 }

6. Use the findAndModify command

A common use case in gaming is finding a profile for a given user and increment a value in the user’s profile. In this scenario, you want to run a promotion for the top active gamers. If the gamer fills out a survey, you increase their score by +10.

To do that, use the findAndModify command. In this use case, the user Tim received and completed a survey. To give Tim the credit to their score, enter the following code:

db.profiles.findAndModify({   query: { name: "Tim", status: "active"},   update: { $inc: { score: 10 } }})

You get the following output:

{      "_id" : 1,      "name" : "Tim",      "status" : "active",      "level" : 12,      "score" : 202}

7. Verify the result

You can verify the result with the following query:

db.profiles.find({name: "Tim"})

You get the following output:

{ "_id" : 1, "name" : "Tim", "status" : "active", "level" : 12, "score" : 212 }

Cleaning up

When you complete the walkthrough, stop your Amazon DocumentDB cluster to reduce costs or delete the cluster altogether.

By default, after 30 minutes of inactivity, your AWS Cloud9 environment stops the underlying EC2 instance to help save costs.

Congratulations

This tutorial showed you how to get started with Amazon DocumentDB by creating an AWS Cloud9 environment.

You were able to install the mongo shell, create an Amazon DocumentDB cluster, connect to your cluster, and perform a few queries, seeing how easy it is to insert and query JSON documents within Amazon DocumentDB.

Amazon DocumentDB (with MongoDB compatibility) is a fast, scalable, highly available, and fully managed document database service that supports MongoDB workloads, and makes it easy to store, query, and index JSON data.