All Products
Search
Document Center

:Connect to a DynamoDB-compatible instance by using program code

Last Updated:Jun 04, 2025

This topic describes how to use the AWS Command Line Interface (AWS CLI) and SDKs for programming languages, such as Python and Java, to connect to a DynamoDB-compatible ApsaraDB for MongoDB instance.

Prerequisites

An ApsaraDB for MongoDB instance compatible with the DynamoDB protocol is created. For more information about how to create an ApsaraDB for MongoDB instance, see Create a sharded cluster instance.

Preparations

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

  1. Log on to the ApsaraDB for MongoDB console.

  2. In the upper-left corner of the page that appears, select the resource group and region to which your instance belongs.

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

  4. Find the desired instance and click the instance ID.

  5. In the left-side navigation pane of the instance details page, click Database Connections.

  6. In the Internal Connections - VPC section, view the connection string of the instance.连接地址

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 the 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 the ECS instance. For more information, see View instance information.

  • The network types of your sharded cluster instance and ECS instance are the same. You can view the network type of the ECS instance. For more information, see View instance information. If the 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 describes how to use the AWS CLI to connect to the DynamoDB-compatible ApsaraDB for MongoDB instance. In this example, Ubuntu 16.04.6 LTS is used. 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 the package 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 file:

      unzip awscliv2.zip
      Note

      If you have not installed the unzip utility, run the sudo 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, 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 and configure the parameters described in the following table. Press the Enter key after you configure a parameter.

    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 region 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 Configure the AWS CLI.

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

    aws dynamodb --endpoint-url <Connection string of the DynamoDB-compatible ApsaraDB for MongoDB instance> \ 
        create-table --table-name <Name of the collection that you want to create> \
        --attribute-definitions AttributeName=<Attribute name>,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. The connection string must start with HTTP://.

    create-table

    The command used to create the collection.

    Note

    For more information, see create-table.

    --table-name

    The name of the collection that you want to create.

    --attribute-definitions

    An array of attributes that describe the key schema for the collection or index. This parameter consists of the following options:

    • AttributeName: the name of the attribute.

    • AttributeType: the data type of the attribute.

      Note

      For more information, see create-table.

    --key-schema

    The primary key attributes of the collection or index. This parameter consists of the following options:

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

    • KeyType: the role of the primary key.

      Note

      For more information, see create-table.

    --provisioned-throughput

    The provisioned throughput for the collection or index. This parameter consists of the following options:

    • ReadCapacityUnits: the provisioned read throughput.

    • WriteCapacityUnits: the provisioned write throughput.

    Note

    For more information, see create-table.

    Sample code:

    /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 collection 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 collection.  \
        --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 to 5.

    If the following content is displayed, you are connected to the DynamoDB-compatible ApsaraDB for MongoDB instance and a collection is created.

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

Use Python to connect to the instance

The following sample code provides an example on how to use SDK for Python to connect to the DynamoDB-compatible ApsaraDB for MongoDB instance and create a collection 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 Java to connect to the instance

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

The following sample code provides an example on how to use SDK for Java to connect to the DynamoDB-compatible ApsaraDB for MongoDB instance and create a collection 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 programming languages to connect to the instance

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