Connect Using Amazon EC2

This section describes how to launch an Amazon DocumentDB (with MongoDB compatibility) cluster using Amazon EC2 and interact with it, using the mongo shell. The video below demonstrates the steps in this guide.

Prerequisites

Before you create your first Amazon DocumentDB cluster, you must do the following:

Create an Amazon Web Services (AWS) account

Before you can begin using Amazon DocumentDB, you must have an Amazon Web Services (AWS) account. The AWS account is free. You pay only for the services and resources that you use.

If you do not have an AWS account, complete the following steps to create one.

To sign up for an AWS account

  1. Open https://portal.aws.amazon.com/billing/signup.

  2. Follow the online instructions.

    Part of the sign-up procedure involves receiving a phone call and entering a verification code on the phone keypad.

Set up the needed AWS Identity and Access Management (IAM) permissions.

Access to manage Amazon DocumentDB resources such as clusters, instances, and cluster parameter groups requires credentials that AWS can use to authenticate your requests. For more information, see Identity and Access Management in Amazon DocumentDB.

  1. In the search bar of the AWS Management Console, type in IAM and select IAM in the drop down menu that appears.

  2. Once you’re in the IAM console, select Users from the navigation pane.

  3. Select your username.

  4. Click the button Add permissions.

  5. Select Attach existing policies directly.

  6. Type AmazonDocDBFullAccess in the search bar and select it once it appears in the search results.

  7. Click the blue button at the bottom that says Next: Review.

  8. Click the blue button at the bottom that says Add permissions.

Create an Amazon Virtual Private Cloud (Amazon VPC)

Depending on which AWS region you are in, you may or may not have a default VPC already created. If you don’t have a default VPC, complete step 1 of the Getting Started with Amazon VPC in the Amazon VPC User Guide. This will take less than five minutes.

Step 1: Create an Amazon EC2 Instance

In this step, you will create an Amazon EC2 instance in the same Region and Amazon VPC that you will later use to provision your Amazon DocumentDB cluster.

  1. On the Amazon EC2 console, choose Launch instance.

    Connect Using Amazon EC2 - 图1

  2. Locate Amazon Linux 2 AMI and choose Select.

    Connect Using Amazon EC2 - 图2

  3. Choose the t3.micro instance type.

    Connect Using Amazon EC2 - 图3

  4. Choose Review and Launch, which will allow you to skip to the console’s Step 7: Review Instance Launch page.

    Connect Using Amazon EC2 - 图4

  5. Under Security Groups, choose Edit security groups.

    Connect Using Amazon EC2 - 图5

  6. This will default to Create a new security group. In the Security group name field, write demoEC2.

    Connect Using Amazon EC2 - 图6

  7. Change Type to SSH. This will automatically set the port range to 22.

    Connect Using Amazon EC2 - 图7

  8. Select the drop down menu for Source and choose My IP.

    Connect Using Amazon EC2 - 图8

    Note

    You can only access the demoEC2 security group from your current IP address. If your IP address changes, you must update the security group.

  9. Now choose Review and Launch. You should now see the demoEC2 security group in the Security Groups section.

    Connect Using Amazon EC2 - 图9

  10. Verify the information and choose Launch.

    Connect Using Amazon EC2 - 图10

  11. A window will pop up titled Select an existing key pair or create a new key pair. It will look like this:

    Connect Using Amazon EC2 - 图11

    You must provide an Amazon EC2 key pair. If you do have an Amazon EC2 key pair:

    1. Select a key pair, choose your key pair from the list.

    2. You must already have the private key file (.pem file) available to log in to your Amazon EC2 instance.

    If you do not have an Amazon EC2 key pair:

    1. Choose Create a new key pair.

    2. Write a name for the key bar in the field Key pair name.

    3. Download the private key file (.pem file). You need this file later when you log in to your Amazon EC2 instance.

  12. Choose Launch Instances.

    Connect Using Amazon EC2 - 图12

Step 2: Create a security group

You will now create a new security group in your default Amazon VPC. The security group demoDocDB enables you to connect to your Amazon DocumentDB cluster on port 27017 (the default port for Amazon DocumentDB) from your Amazon EC2 instance.

  1. On the Amazon EC2 console, under Network and Security, choose Security groups.

    Connect Using Amazon EC2 - 图13

  2. Choose Create security group.

    Connect Using Amazon EC2 - 图14

  3. For Security group name, enter demoDocDB.

    Connect Using Amazon EC2 - 图15

  4. For Description, enter a description.

    Connect Using Amazon EC2 - 图16

  5. For VPC, accept the usage of your default VPC.

  6. In the Inbound rules section, choose Add rule.

    Connect Using Amazon EC2 - 图17

  7. For Type, choose Custom TCP Rule.

    Connect Using Amazon EC2 - 图18

  8. For Port range, enter 27017.

    Connect Using Amazon EC2 - 图19

  9. For Destination, choose Custom. In the field next to it, search for the security group you just made called demoEC2. You may need to refresh your browser for the Amazon EC2 console to auto-populate the demoEC2 source name.

    Connect Using Amazon EC2 - 图20

  10. Accept all other defaults and choose Create security group.

    Connect Using Amazon EC2 - 图21

Step 3: Create an Amazon DocumentDB Cluster

While the Amazon EC2 instance is being provisioned, you will create your Amazon DocumentDB cluster.

  1. Navigate to the Amazon DocumentDB console and choose Clusters from the navigation pane.

    Connect Using Amazon EC2 - 图22

  2. Choose Create.

    Connect Using Amazon EC2 - 图23

  3. For Number of instances, choose 1. This will minimize cost. Leave other settings at their default.

    Connect Using Amazon EC2 - 图24

  4. For Authentication, enter a username and password. Important: You will need this username and password to authenticate your cluster in a later step.

    Connect Using Amazon EC2 - 图25

  5. Turn on Show advanced settings.

    Connect Using Amazon EC2 - 图26

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

    Connect Using Amazon EC2 - 图27

  7. Choose Create cluster.

    Connect Using Amazon EC2 - 图28

Step 4: Connect to your Amazon EC2 instance

To install the mongo shell, you must first connect to your Amazon EC2 instance. Installing the mongo shell enables you to connect to and query your Amazon DocumentDB cluster. Complete the following steps:

  1. On the Amazon EC2 console, navigate to your instances and see if the instance you just created is running. If it is, select the instance.

    Connect Using Amazon EC2 - 图29

  2. Choose Connect.

    Connect Using Amazon EC2 - 图30

  3. You will see three options for your connection method: Amazon EC2 Instance Connect, Session Manager, or SSH client. You must choose one and follow its instructions.

    Connect Using Amazon EC2 - 图31

Note

If your IP address changed after you started this walkthrough, or you are coming back to your environment at a later time, you must update your demoEC2 security group inbound rule to enable inbound traffic from your new API address.

Step 5: Install the mongo shell

You can now install the mongo shell, which is a command-line utility that you use to connect and query your Amazon DocumentDB cluster. Follow the instructions below to install the mongo shell for your operating system.

To install the mongo shell on Amazon Linux

  1. Create the repository file. At the command line of your EC2 instance, execute the follow command:

    1. 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
  2. When it is complete, install the mongo shell by executing the following command:

    1. sudo yum install -y mongodb-org-shell

To install the mongo shell on Ubuntu 18.04

  1. Import the public key that will be used by the package management system.

    1. sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2930ADAE8CAF5059EE73BB4B58712A2291FA4AD5
  2. Create the list file /etc/apt/sources.list.d/mongodb-org-3.6.list for MongoDB using the command appropriate for your version of Ubuntu.

    Ubuntu 18.04

    1. echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.6.list

    Note

    The command above will install the mongo 3.6 shell for both Bionic and Xenial.

  3. Reload the local package database using the following command:

    1. sudo apt-get update
  4. Install the MongoDB shell.

    1. sudo apt-get install -y mongodb-org-shell

For information about installing earlier versions of MongoDB on your Ubuntu system, see Install MongoDB Community Edition on Ubuntu.

To install the mongo shell on other operating systems, see Install MongoDB Community Edition in the MongoDB documentation.

Step 6: Manage Amazon DocumentDB TLS

Download the CA certificate for Amazon DocumentDB with the following code: wget https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem

Note

Transport Layer Security (TLS) is enabled by default for any new Amazon DocumentDB clusters. For more information, see Managing Amazon DocumentDB Cluster TLS Settings.

Step 7: Connect to your Amazon DocumentDB cluster

  1. On the Amazon Document DB console, under Clusters, locate your cluster. Choose the cluster you created.

    Connect Using Amazon EC2 - 图32

  2. Navigate to the Connection box. It will look like this.

    Connect Using Amazon EC2 - 图33

    Copy the connection string provided.

    Connect Using Amazon EC2 - 图34

    After you paste it into your terminal and make the following changes to it: first, make sure you have the correct username in the string. Then, omit <insertYourPassword> so that you are prompted for the password by the mongo shell when you connect. Your connection string should look similar to the following:

    mongo --ssl host docdb-2020-02-08-14-15-11. cluster.region.docdb.amazonaws.com:27107 --sslCAFile rds-combined-ca-bundle.pem --username demoUser --password

  3. Now press enter in your terminal. You will now be prompted for your password. Enter your password.

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

Having problems connecting? See Troubleshooting Amazon DocumentDB.

Step 8: 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. To insert a single document, enter the following:

    1. db.collection.insert({"hello":"DocumentDB"})
  2. You get the following output:

    WriteResult({ "nInserted" : 1 })

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

    1. db.collection.findOne()
  4. You get the following output:

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

  5. To perform a few more queries, consider a gaming profiles use case. First, insert a few entries into a collection titled profiles. Input the following:

    1. db.profiles.insertMany([
    2. { "_id" : 1, "name" : "Matt", "status": "active", "level": 12, "score":202},
    3. { "_id" : 2, "name" : "Frank", "status": "inactive", "level": 2, "score":9},
    4. { "_id" : 3, "name" : "Karen", "status": "active", "level": 7, "score":87},
    5. { "_id" : 4, "name" : "Katie", "status": "active", "level": 3, "score":27}
    6. ])
  6. You get the following output:

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

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

    1. db.profiles.find()
  8. You will get an output that will match the data you typed in Step 5.

  9. Use a query for a single document using a filter. Input the following:

    1. db.profiles.find({name: "Katie"})
  10. You should get back this output:

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

  11. Now let’s try to find a profile and modify it using the findAndModify command. We’ll give the user Matt an extra ten points with the following code:

    1. db.profiles.findAndModify({
    2. query: { name: "Matt", status: "active"},
    3. update: { $inc: { score: 10 } }
    4. })
  12. You get the following output (note that his score hasn’t increased yet):

    1. {
    2. "_id" : 1,
    3. "name" : "Matt",
    4. "status" : "active",
    5. "level" : 12,
    6. "score" : 202
    7. }
  13. You can verify that his score has changed with the following query:

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

  14. You get the following output:

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

Step 9: Explore

Congratulations! You have successfully completed the Quick Start Guide to Amazon DocumentDB.

What’s next? Learn how to fully leverage this powerful database with some of its popular features:

Note

To save on cost, you can either stop your Amazon DocumentDB cluster to reduce costs or delete the cluster. By default, after 30 minutes of inactivity, your AWS Cloud9 environment will stop the underlying Amazon EC2 instance.