All Products
Search
Document Center

ApsaraDB for MongoDB:Connect to a DynamoDB-compatible ApsaraDB for MongoDB instance by using application code

Last Updated:Apr 22, 2024

This topic describes how to connect to a DynamoDB-compatible ApsaraDB for MongoDB instance by using the Amazon Web Services (AWS) CLI and SDKs for programing languages such as Python and Java.

Prerequisites

A DynamoDB-compatible sharded cluster instance is created. To create a DynamoDB-compatible instance, you must select the DynamoDB protocol. For more information about how to create a DynamoDB-compatible instance, see Create a sharded cluster instance.

Preparations

  • Obtain the connection string of a DynamoDB-compatible ApsaraDB for MongoDB instance.

    1. Log on to the ApsaraDB for MongoDB console.

    2. In the top navigation bar, select the resource group and region to which the sharded cluster instance belongs.

    3. In the left-side navigation pane, click Sharded Cluster Instances.

    4. On the page that appears, find the instance and click its ID.

    5. In the left-side navigation pane, click Database Connection.

    6. In the Internal Connections - VPC section, view the connection string of the instance. Connection string

  • Optional:If your application is deployed on an Elastic Compute Service (ECS) instance, make sure that your sharded cluster instance and the ECS instance meet the following requirements to ensure network connectivity:

    • Your sharded cluster instance and the ECS instance belong to the same region. You can view the region of a created ECS instance. For more information, see View instance information.

    • Optional:Your sharded cluster instance and the ECS instance belong to the same zone. This reduces network latency. You can view the zone of a created ECS instance. For more information, see View instance information.

    • Your sharded cluster instance and the ECS instance reside in the same type of network. You can view the network type of a created ECS instance. For more information, see View instance information. If an ECS instance resides in the classic network, you can migrate the ECS instance from the classic network to a virtual private cloud (VPC). For more information, see Migrate ECS instances from the classic network to a VPC.

Use the AWS CLI to connect to the instance

This section demonstrates how to use the AWS CLI to connect to the DynamoDB-compatible ApsaraDB for MongoDB instance. Ubuntu 16.04.6 LTS is used in the example. For more information about the AWS CLI, see What is the AWS Command Line Interface?

  1. Install the AWS CLI client.

    1. Run the following command to obtain the installation package of the latest AWS CLI version and rename it awscliv2.zip:

      curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
    2. Run the following command to decompress the awscliv2.zip package:

      unzip awscliv2.zip
      Note

      If you have not installed the unzip utility, run the apt install unzip command to install the unzip utility. Then, run the preceding command to decompress the awscliv2.zip package.

    3. Run the following command to install the AWS CLI client:

      sudo ./aws/install

    If the You can now run: /usr/local/bin/aws --version prompt appears in the CLI window, the AWS CLI client is installed. You can run the /usr/local/bin/aws --version command to query the version number of the AWS CLI.

  2. Run the /usr/local/bin/aws configure command to configure the AWS CLI by specifying the parameters listed in the following table. Each time you specify a parameter, you must press the Enter key.

    Parameter

    Description

    Example

    AWS Access Key ID

    The access key ID of your AWS account. If you do not have an access key ID, enter random characters.

    XXXXXXXXXX

    AWS Secret Access Key

    The secret access key of your AWS account. If you do not have a secret access key, enter random characters.

    XXXXXXXXXX

    Default region name

    The region where your AWS DynamoDB database resides. If you do not have a region, enter the one in the example.

    us-west-2

    Default output format

    The default output format. This parameter can be left empty.

    json

    Note

    For more information about AWS CLI configurations, see Configuration basics.

  3. Run the following command to connect to the DynamoDB-compatible ApsaraDB for MongoDB instance and create a table:

    aws dynamodb --endpoint-url <Connection string of the DynamoDB-compatible ApsaraDB for MongoDB instance> \ 
        create-table --table-name <Name of the table that you want to create> \
        --attribute-definitions AttributeName=<Name of the attribute>,AttributeType=<Data type of the attribute> \
        --key-schema AttributeName=<Attribute name of the primary key>,KeyType=<Role of the primary key> \
        --provisioned-throughput ReadCapacityUnits=<Provisioned read throughput>,WriteCapacityUnits=<Provisioned write throughput>

    Parameter

    Description

    --endpoint-url

    The connection string of the DynamoDB-compatible ApsaraDB for MongoDB instance. It must start with HTTP://.

    create-table

    The command used to create the table.

    Note

    For more information, see create-table.

    --table-name

    The name of the table that you want to create.

    --attribute-definitions

    An array of attributes that describe the key schema for the table and indexes. This parameter consists of the following attributes:

    • AttributeName: the name of the attribute.

    • AttributeType: the data type of the attribute.

      Note

      For more information, see create-table.

    --key-schema

    The attributes that make up the primary key for a table or an index. This parameter consists of the following attributes:

    • AttributeName: the name of the key attribute that is created by using the --attribute-definitions parameter.

    • KeyType: the role of the key attribute.

      Note

      For more information, see create-table.

    --provisioned-throughput

    The provisioned throughput settings for a table or an index. This parameter consists of the following attributes:

    • ReadCapacityUnits: the provisioned read throughput.

    • WriteCapacityUnits: the provisioned write throughput.

    Note

    For more information, see create-table.

    Example:

    /usr/local/bin/aws dynamodb --endpoint-url http://dds-xxxx.mongodb.rds.aliyuncs.com:3717 #Specify the connection string used to connect to the DynamoDB-compatible ApsaraDB for MongoDB instance.  \
        create-table --table-name student #Create a table named student.  \
        --attribute-definitions AttributeName=name,AttributeType=S AttributeName=age,AttributeType=N #Specify a STRING-typed name attribute and a NUMBER-typed age attribute for the table.  \
        --key-schema AttributeName=name,KeyType=HASH AttributeName=age,KeyType=RANGE #Specify the name attribute as a partition key and the age attribute as a sort key.  \
        --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 #Set the provisioned read throughput and write throughput both to 5. 

    When the following content is displayed in the command output, you are connected to the DynamoDB-compatible ApsaraDB for MongoDB instance and a table is created.

    {
        "TableDescription": {
            "TableName": "student",
            "KeySchema": [
                {
                    "AttributeName": "name",
                    "KeyType": "HASH"
                },
                {
                    "AttributeName": "age",
                    "KeyType": "RANGE"
                }
            ],
            "TableStatus": "CREATING",
            "TableSizeBytes": 0,
            "ItemCount": 0
        }
    }
                            

Use the SDK for Python to connect to the instance

The following sample code shows how to use the SDK for Python to connect to the DynamoDB-compatible ApsaraDB for MongoDB instance and create a table named Book:

import boto3

def create_book_table(dynamodb=None):
 if not dynamodb:
 dynamodb = boto3.resource('dynamodb', endpoint_url="http://dds-xxxx.mongodb.rds.aliyuncs.com:3717")
 table = dynamodb.create_table(
 TableName='Book',
 KeySchema=[
 {
 'AttributeName':'title',
 'KeyType':'HASH'
 },
 {
 'AttributeName':'year',
 'KeyType':'RANGE'
 }
 ],
 AttributeDefinitions=[
 {
 'AttributeName':'title',
 'AttributeType':'S'
 },
 {
 'AttributeName':'year',
 'AttributeType':'N'
 },
 ],
 ProvisionedThroughput={
 'ReadCapacityUnits':5,
 'WriteCapacityUnits':5
 }
 )
 return table

if __name__ == '__main__':
 book_table =create_book_table()
 print("Tablestatus:", book_table.table_status)

Use the SDK for Java to connect to the instance

Install AWS SDK for Java. For more information, see Setting up the AWS SDK for Java 2.x.

The following sample code shows how to use the SDK for Java to connect to the DynamoDB-compatible ApsaraDB for MongoDB instance and create a table named Book:

package com.amazonaws.codesamples.gsg;

import java.util.Arrays;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder;
import com.amazonaws.services.dynamodbv2.document.DynamoDB;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.dynamodbv2.model.AttributeDefinition;
import com.amazonaws.services.dynamodbv2.model.KeySchemaElement;
import com.amazonaws.services.dynamodbv2.model.KeyType;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ScalarAttributeType;

public class MoviesCreateTable {
 public static void main(String[] args) throws Exception {
 
        AmazonDynamoDB client =AmazonDynamoDBClientBuilder.standard()
            .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://dds-xxxx.mongodb.rds.aliyuncs.com:3717",
"us-east-1"))
            .build();

 DynamoDB dynamoDB = new DynamoDB(client);

 String tableName ="Book";

 try {
 System.out.println("Creating table...");
 Table table =dynamoDB.createTable(tableName,
 Arrays.asList(new
KeySchemaElement("title", KeyType.HASH), // Partition key
                    new KeySchemaElement("year", KeyType.RANGE)), // Sort key
 Arrays.asList(new AttributeDefinition("title", ScalarAttributeType.S),
 new AttributeDefinition("year", ScalarAttributeType.N)),
 new ProvisionedThroughput(5L, 5L));
 table.waitForActive();
System.out.println("OK. Table status: " + table.getDescription().getTableStatus());
 }
 catch (Exception e) {
System.err.println("Unable to create table: ");
System.err.println(e.getMessage());
 }
 }
}

Use SDKs for other programing languages to connect to the instance

For more information, see Getting Started with DynamoDB and AWS SDKs.