

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 以编程方式连接到 Amazon DocumentDB
以编程方式连接

本部分包含说明了如何使用多种不同语言连接到 Amazon DocumentDB（与 MongoDB 兼容）的代码示例。根据连接的集群是否启用传输层安全性 (TLS)，这些示例分为两个部分。默认情况下，Amazon DocumentDB 集群启用了 TLS。但是，您可以根据需要关闭 TLS。有关更多信息，请参阅 [加密传输中数据](security.encryption.ssl.md)。

如果您想要从集群所在的 VPC 之外连接到 Amazon DocumentDB，请参阅[从 Amazon VPC 外部连接到 Amazon DocumentDB 集群](connect-from-outside-a-vpc.md)。

在连接到集群之前，您必须知道集群是否启用了 TLS。下一部分介绍如何使用 `tls`或 Amazon Web Services 管理控制台 确定集群的 Amazon CLI 参数的值。之后，您可以查找和应用适当的代码示例。

**Topics**
+ [

## 确定 `tls` 参数的值
](#connect_programmatically-determine_tls_value)
+ [

## 启用了 TLS 的情况下的连接
](#connect_programmatically-tls_enabled)
+ [

## 禁用了 TLS 的情况下的连接
](#connect_programmatically-tls_disabled)

## 确定 `tls` 参数的值
确定 `tls` 值

确定集群是否启用了 TLS 是一个两步过程，您可以使用 Amazon Web Services 管理控制台或 Amazon CLI 执行该过程。

1. **确定管理集群的参数组。**

------
#### [ Using the Amazon Web Services 管理控制台 ]

   1. 登录到 Amazon Web Services 管理控制台 并打开 Amazon DocumentDB 控制台，网址：[https://console.aws.amazon.com/docdb](https://console.amazonaws.cn/docdb)。

   1. 在左侧导航窗格中，选择**集群**。

   1. 在集群列表中，选择您的集群的名称。

   1. 生成的页面将显示所选集群的详细信息。选择 **Configuration（配置）**选项卡。在**配置和状态**部分中，在**集群参数组**下找到参数组的名称。

------
#### [ Using the Amazon CLI ]

   使用以下 Amazon CLI 代码可以确定管理您的集群的参数。请确保将 *`sample-cluster`* 替换为您的集群的名称。

   ```
   aws docdb describe-db-clusters \
       --db-cluster-identifier sample-cluster \
       --query 'DBClusters[*].[DBClusterIdentifier,DBClusterParameterGroup]'
   ```

   此操作的输出将类似于以下内容：

   ```
   [
          [
              "sample-cluster",
              "sample-parameter-group"
          ]
   ]
   ```

------

1. **确定您的集群参数组中的 `tls` 参数的值。**

------
#### [ Using the Amazon Web Services 管理控制台 ]

   1. 在导航窗格中，选择**参数组**。

   1. 在**集群参数组**窗口中，选择您在步骤 1d 中创建的集群参数组名称。

   1. 打开的页面上会显示您的集群参数组中包含的参数。您可以在其中查看 `tls` 参数的值。有关修改此参数的信息，请参阅[修改 Amazon DocumentDB 集群参数组](cluster_parameter_groups-modify.md)。

------
#### [ Using the Amazon CLI ]

   您可以使用 `describe-db-cluster-parameters` Amazon CLI 命令来查看集群参数组中的参数的详细信息。
   + **`--describe-db-cluster-parameters`** — 列出参数组中的所有参数及其值。
     + **`--db-cluster-parameter-group name`** – 必需。您的集群参数组的名称。

   在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

   ```
   aws docdb describe-db-cluster-parameters \
       --db-cluster-parameter-group-name sample-parameter-group
   ```

   此操作的输出将类似于以下内容：

   ```
   {
           "Parameters": [
               {
                   "ParameterName": "profiler_threshold_ms",
                   "ParameterValue": "100",
                   "Description": "Operations longer than profiler_threshold_ms will be logged",
                   "Source": "system",
                   "ApplyType": "dynamic",
                   "DataType": "integer",
                   "AllowedValues": "50-2147483646",
                   "IsModifiable": true,
                   "ApplyMethod": "pending-reboot"
               },
               {
                   "ParameterName": "tls",
                   "ParameterValue": "disabled",
                   "Description": "Config to enable/disable TLS",
                   "Source": "user",
                   "ApplyType": "static",
                   "DataType": "string",
                   "AllowedValues": "disabled,enabled,fips-140-3",
                   "IsModifiable": true,
                   "ApplyMethod": "pending-reboot"
               }
           ]
   }
   ```

**注意**  
Amazon DocumentDB 支持以下区域中从 Amazon DocumentDB 5.0（引擎版本 3.0.3727）集群开始的 FIPS 140-3 端点：ca-central-1、us-west-2、us-east-1、us-east-2、us-gov-east-1、us-gov-west-1。

------

确定 `tls` 参数的值后，即可使用以下部分中的代码示例之一继续连接到您的集群。
+ [启用了 TLS 的情况下的连接](#connect_programmatically-tls_enabled) 
+ [禁用了 TLS 的情况下的连接](#connect_programmatically-tls_disabled) 

## 启用了 TLS 的情况下的连接


要查看以编程方式连接到启用了 TLS 的 Amazon DocumentDB 集群的代码示例，请选择您要使用的语言所对应的选项卡。

要加密传输中数据，请使用以下操作下载名为 `rds-combined-ca-cn-bundle.pem` 的 Amazon DocumentDB 公钥。

```
wget https://s3.cn-north-1.amazonaws.com.cn/rds-downloads/rds-combined-ca-cn-bundle.pem
```

如果您的应用程序在 Microsoft Windows 上并且需要 PKCS7 文件，则可以下载 PKCS7 证书捆绑包。该捆绑包包含位于 [ https://truststore.pki.rds.amazonaws.com/global/global-bundle.p7b](https://truststore.pki.rds.amazonaws.com/global/global-bundle.p7b) 的中间证书和根证书。

------
#### [ Python ]

以下代码说明了如何在启用了 TLS 的情况下使用 Python 连接到 Amazon DocumentDB。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

```
import pymongo
import sys

##Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set and specify the read preference as secondary preferred
client = pymongo.MongoClient('mongodb://sample-user:password@sample-cluster.node.cn-north-1.docdb.amazonaws.com:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred') 

##Specify the database to be used
db = client.sample_database

##Specify the collection to be used
col = db.sample_collection

##Insert a single document
col.insert_one({'hello':'Amazon DocumentDB'})

##Find the document that was previously written
x = col.find_one({'hello':'Amazon DocumentDB'})

##Print the result to the screen
print(x)

##Close the connection
client.close()
```

------
#### [ Node.js ]

以下代码说明了如何在启用了 TLS 的情况下使用 Node.js 连接到 Amazon DocumentDB。

**重要**  
低于版本 6.13.1 的 Node.js 驱动程序存在已知限制，Amazon DocumentDB 目前不支持用这种驱动程序进行 IAM 身份验证。必须升级 Node.js 驱动程序以及使用 Node.js 驱动程序的工具（例如 mongosh），以使用 Node.js 驱动程序版本 6.13.1 或更高版本。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

```
var MongoClient = require('mongodb').MongoClient,
  f = require('util').format,
  fs = require('fs');

//Specify the Amazon DocumentDB cert
var ca = [fs.readFileSync("global-bundle.pem")];

//Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set, 
//  and specify the read preference as secondary preferred
var client = MongoClient.connect(
'mongodb://sample-user:password@sample-cluster.node.cn-north-1.docdb.amazonaws.com:27017/sample-database?ssl=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false', 
{ 
  sslValidate: true,
  sslCA:ca,
  useNewUrlParser: true
},
function(err, client) {
    if(err)
        throw err;
        
    //Specify the database to be used
    db = client.db('sample-database');
    
    //Specify the collection to be used
    col = db.collection('sample-collection');

    //Insert a single document
    col.insertOne({'hello':'Amazon DocumentDB'}, function(err, result){
      //Find the document that was previously written
      col.findOne({'hello':'Amazon DocumentDB'}, function(err, result){
        //Print the result to the screen
        console.log(result);
        
        //Close the connection
        client.close()
      });
   });
});
```

------
#### [ PHP ]

以下代码说明了如何在启用了 TLS 的情况下使用 PHP 连接到 Amazon DocumentDB。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

```
<?php
//Include Composer's autoloader
require 'vendor/autoload.php';

$SSL_DIR = "/home/ubuntu";
$SSL_FILE = "global-bundle.pem";

//Specify the Amazon DocumentDB cert
$ctx = stream_context_create(array(
    "ssl" => array(
        "cafile" => $SSL_DIR . "/" . $SSL_FILE,
    ))
);

//Create a MongoDB client and open connection to Amazon DocumentDB
$client = new MongoDB\Client("mongodb://sample-user:password@sample-cluster.node.cn-north-1.docdb.amazonaws.com:27017/?retryWrites=false", array("ssl" => true), array("context" => $ctx));

//Specify the database and collection to be used
$col = $client->sampledatabase->samplecollection;

//Insert a single document
$result = $col->insertOne( [ 'hello' => 'Amazon DocumentDB'] );

//Find the document that was previously written
$result = $col->findOne(array('hello' => 'Amazon DocumentDB'));

//Print the result to the screen
print_r($result);
?>
```

------
#### [ Go ]

以下代码说明了如何在启用了 TLS 的情况下使用 Go 连接到 Amazon DocumentDB。

**注意**  
从版本 1.2.1 开始，MongoDB Go 驱动程序将仅使用在 `sslcertificateauthorityfile` 中找到的第一个 CA 服务器证书。以下代码示例通过将在 `sslcertificateauthorityfile` 中找到的所有服务器证书手动附加到在创建客户端期间使用的自定义 TLS 配置来解决此限制。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

```
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"

	"io/ioutil"
	"crypto/tls"
	"crypto/x509"
	"errors"
)

const (
	// Path to the AWS CA file
	caFilePath = "global-bundle.pem"

	// Timeout operations after N seconds
	connectTimeout  = 5
	queryTimeout    = 30
	username        = "sample-user"
	password        = "password"
	clusterEndpoint = "sample-cluster.node.cn-north-1.docdb.amazonaws.com:27017"

	// Which instances to read from
	readPreference = "secondaryPreferred"

	connectionStringTemplate = "mongodb://%s:%s@%s/sample-database?tls=true&replicaSet=rs0&readpreference=%s"
)

func main() {

	connectionURI := fmt.Sprintf(connectionStringTemplate, username, password, clusterEndpoint, readPreference)

	tlsConfig, err := getCustomTLSConfig(caFilePath)
	if err != nil {
		log.Fatalf("Failed getting TLS configuration: %v", err)
	}

	client, err := mongo.NewClient(options.Client().ApplyURI(connectionURI).SetTLSConfig(tlsConfig))
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), connectTimeout*time.Second)
	defer cancel()

	err = client.Connect(ctx)
	if err != nil {
		log.Fatalf("Failed to connect to cluster: %v", err)
	}

	// Force a connection to verify our connection string
	err = client.Ping(ctx, nil)
	if err != nil {
		log.Fatalf("Failed to ping cluster: %v", err)
	}

	fmt.Println("Connected to DocumentDB!")

	collection := client.Database("sample-database").Collection("sample-collection")

	ctx, cancel = context.WithTimeout(context.Background(), queryTimeout*time.Second)
	defer cancel()

	res, err := collection.InsertOne(ctx, bson.M{"name": "pi", "value": 3.14159})
	if err != nil {
		log.Fatalf("Failed to insert document: %v", err)
	}

	id := res.InsertedID
	log.Printf("Inserted document ID: %s", id)

	ctx, cancel = context.WithTimeout(context.Background(), queryTimeout*time.Second)
	defer cancel()

	cur, err := collection.Find(ctx, bson.D{})

	if err != nil {
		log.Fatalf("Failed to run find query: %v", err)
	}
	defer cur.Close(ctx)

	for cur.Next(ctx) {
		var result bson.M
		err := cur.Decode(&result)
		log.Printf("Returned: %v", result)

		if err != nil {
			log.Fatal(err)
		}
	}

	if err := cur.Err(); err != nil {
		log.Fatal(err)
	}

}

func getCustomTLSConfig(caFile string) (*tls.Config, error) {
	tlsConfig := new(tls.Config)
	certs, err := ioutil.ReadFile(caFile)

	if err != nil {
		return tlsConfig, err
	}

	tlsConfig.RootCAs = x509.NewCertPool()
	ok := tlsConfig.RootCAs.AppendCertsFromPEM(certs)

	if !ok {
		return tlsConfig, errors.New("Failed parsing pem file")
	}

	return tlsConfig, nil
}
```

------
#### [ Java ]

从 Java 应用程序连接到启用了 TLS 的 Amazon DocumentDB 集群时，您的程序必须使用 Amazon 提供的证书颁发机构（CA）文件验证连接。要使用 Amazon RDS CA 证书，请执行以下操作：

1. 从 [https://rds-truststore.s3.cn-north-1.amazonaws.com.cn/global/global-bundle.pem](https://rds-truststore.s3.cn-north-1.amazonaws.com.cn/global/global-bundle.pem) 下载 Amazon RDS CA 文件。

1. 通过执行以下命令，使用该文件中包含的 CA 证书来创建信任存储。请务必将 *truststore-password* 更改为其他内容。如果您要访问同时包含旧 CA 证书 (`rds-ca-2015-root.pem`) 和新 CA 证书 (`rds-ca-2019-root.pem`) 的信任存储，可以将证书捆绑包导入该信任存储。

   下面是一个示例 Shell 脚本，它将证书捆绑包导入 Linux 操作系统上的信任存储。在以下示例中，将每个 *user input placeholder* 替换为您自己的信息。最值得注意的是，无论脚本中示例目录“*mydir*”位于何处，都应将其替换为您为此任务创建的目录。

   ```
   mydir=/tmp/certs
   truststore=${mydir}/rds-truststore.jks
   storepassword=truststore-password
   
   curl -sS "https://rds-truststore.s3.cn-north-1.amazonaws.com.cn/global/global-bundle.pem" > ${mydir}/global-bundle.pem
   awk 'split_after == 1 {n++;split_after=0} /-----END CERTIFICATE-----/ {split_after=1}{print > "rds-ca-" n ".pem"}' < ${mydir}/global-bundle.pem
   
   for CERT in rds-ca-*; do
     alias=$(openssl x509 -noout -text -in $CERT | perl -ne 'next unless /Subject:/; s/.*(CN=|CN = )//; print')
     echo "Importing $alias"
     keytool -import -file ${CERT} -alias "${alias}" -storepass ${storepassword} -keystore ${truststore} -noprompt
     rm $CERT
   done
   
   rm ${mydir}/global-bundle.pem
   
   echo "Trust store content is: "
   
   keytool -list -v -keystore "$truststore" -storepass ${storepassword} | grep Alias | cut -d " " -f3- | while read alias 
   do
      expiry=`keytool -list -v -keystore "$truststore" -storepass ${storepassword} -alias "${alias}" | grep Valid | perl -ne 'if(/until: (.*?)\n/) { print "$1\n"; }'`
      echo " Certificate ${alias} expires in '$expiry'" 
   done
   ```

   下面是一个示例 Shell 脚本，它将证书捆绑包导入 macOS 上的信任存储。

   ```
   mydir=/tmp/certs
   truststore=${mydir}/rds-truststore.jks
   storepassword=truststore-password
   
   curl -sS "https://rds-truststore.s3.cn-north-1.amazonaws.com.cn/global/global-bundle.pem" > ${mydir}/global-bundle.pem
   split -p "-----BEGIN CERTIFICATE-----" ${mydir}/global-bundle.pem
   
   for CERT in rds-ca-*; do
     alias=$(openssl x509 -noout -text -in $CERT | perl -ne 'next unless /Subject:/; s/.*(CN=|CN = )//; print')
     echo "Importing $alias"
     keytool -import -file ${CERT} -alias "${alias}" -storepass ${storepassword} -keystore ${truststore} -noprompt
     rm $CERT
   done
   
   rm ${mydir}/global-bundle.pem
   
   echo "Trust store content is: "
   
   keytool -list -v -keystore "$truststore" -storepass ${storepassword} | grep Alias | cut -d " " -f3- | while read alias 
   do
      expiry=`keytool -list -v -keystore "$truststore" -storepass ${storepassword} -alias "${alias}" | grep Valid | perl -ne 'if(/until: (.*?)\n/) { print "$1\n"; }'`
      echo " Certificate ${alias} expires in '$expiry'" 
   done
   ```

1. 请先在您的应用程序中设置以下系统属性，以便在该程序中使用 `keystore`，然后再连接到 Amazon DocumentDB 集群。

   ```
   javax.net.ssl.trustStore: truststore
   javax.net.ssl.trustStorePassword: truststore-password;
   ```

1. 以下代码说明了如何在启用了 TLS 的情况下使用 Java 连接到 Amazon DocumentDB。

   在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

   ```
   package com.example.documentdb;
   
   import com.mongodb.client.*;
   import org.bson.Document;
   
   public final class Test {
       private Test() {
       }
       public static void main(String[] args) {
   
           String template = "mongodb://%s:%s@%s/sample-database?ssl=true&replicaSet=rs0&readpreference=%s";
           String username = "sample-user";
           String password = "password";
           String clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
           String readPreference = "secondaryPreferred";
           String connectionString = String.format(template, username, password, clusterEndpoint, readPreference);
   
           String truststore = "truststore";
           String truststorePassword = "truststore-password";
   
           System.setProperty("javax.net.ssl.trustStore", truststore);
           System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
   
           MongoClient mongoClient = MongoClients.create(connectionString);
   
           MongoDatabase testDB = mongoClient.getDatabase("sample-database");
           MongoCollection<Document> numbersCollection = testDB.getCollection("sample-collection");
   
           Document doc = new Document("name", "pi").append("value", 3.14159);
           numbersCollection.insertOne(doc);
   
           MongoCursor<Document> cursor = numbersCollection.find().iterator();
           try {
               while (cursor.hasNext()) {
                   System.out.println(cursor.next().toJson());
               }
           } finally {
               cursor.close();
           }
   
       }
   }
   ```

------
#### [ C\$1 / .NET ]

以下代码说明了如何在启用了 TLS 的情况下使用 C\$1 / .NET 连接到 Amazon DocumentDB。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

```
using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using MongoDB.Driver;
using MongoDB.Bson;

namespace DocDB
{
    class Program
    {
        static void Main(string[] args)
        {
            string template = "mongodb://{0}:{1}@{2}/sample-database?ssl=true&replicaSet=rs0&readpreference={3}";
            string username = "sample-user";
            string password = "password";
            string readPreference = "secondaryPreferred";
            string clusterEndpoint="sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
            string connectionString = String.Format(template, username, password, clusterEndpoint, readPreference);
            
            string pathToCAFile = "path_to_global-bundle.p7b_file";

            // ADD CA certificate to local trust store
            // DO this once - Maybe when your service starts
            X509Store localTrustStore = new X509Store(StoreName.Root);
            X509Certificate2Collection certificateCollection = new X509Certificate2Collection();
            certificateCollection.Import(pathToCAFile);
            try 
            {
                localTrustStore.Open(OpenFlags.ReadWrite);
                localTrustStore.AddRange(certificateCollection);
            } 
            catch (Exception ex) 
            {
                Console.WriteLine("Root certificate import failed: " + ex.Message);
                throw;
            } 
            finally 
            {
                localTrustStore.Close();
            }

            var settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
            var client = new MongoClient(settings);

            var database = client.GetDatabase("sample-database");
            var collection = database.GetCollection<BsonDocument>("sample-collection");
            var docToInsert = new BsonDocument { { "pi", 3.14159 } };
            collection.InsertOne(docToInsert);
        }
    }
}
```

------
#### [ MongoDB Shell ]

以下代码演示了如何在启用 TLS 的情况下，使用最新版本 mongosh 或先前的 mongo Shell 版本连接和查询 Amazon DocumentDB。

**使用 mongosh 连接到 Amazon DocumentDB**

**重要**  
低于版本 6.13.1 的 Node.js 驱动程序存在已知限制，Amazon DocumentDB 目前不支持用这种驱动程序进行 IAM 身份验证。必须升级 Node.js 驱动程序以及使用 Node.js 驱动程序的工具（例如 mongosh），以使用 Node.js 驱动程序版本 6.13.1 或更高版本。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

**使用先前的 mongo Shell 版本连接到 Amazon DocumentDB**

如果您使用 IAM，则必须使用先前版本的 mongo Shell。输入以下命令选项之一：

```
mongo --ssl --host <cluster-end-point>:27017 --sslCAFile global-bundle.pem --username sample-user --password password
```

如果您使用的版本等于或高于 4.2，请使用以下代码进行连接。Amazon DocumentDB 不支持可重试写入。如果您使用旧版 mongo Shell（而非 mongosh），不要在任何代码字符串中包含 `retryWrites=false` 命令。默认情况下，禁用可重试写入。包含 `retryWrites=false` 可能导致正常读取命令失败。

```
mongo --tls --host cluster-end-point:27017 --tlsCAFile global-bundle.pem --username sample-user --password password
```

**测试连接**

1. 插入单个文档。

   ```
   db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
   ```

1. 查找以前插入的文档。

   ```
   db.myTestCollection.find({'hello':'Amazon DocumentDB'})
   ```

------
#### [ R ]

以下代码说明了如何在启用了 TLS 的情况下使用 mongolite ([https://jeroen.github.io/mongolite/](https://jeroen.github.io/mongolite/)) 通过 R 连接到 Amazon DocumentDB。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

```
#Include the mongolite library.
library(mongolite)

mongourl <- paste("mongodb://sample-user:password@sample-cluster.node.cn-north-1.docdb.amazonaws.com:27017/test2?ssl=true&",
          "readPreference=secondaryPreferred&replicaSet=rs0", sep="")
          
#Create a MongoDB client, open a connection to Amazon DocumentDB as a replica
#   set and specify the read preference as secondary preferred
client <-  mongo(url = mongourl, options = ssl_options(weak_cert_validation = F, ca ="<PATH/rds-combined-ca-bundle.pem>"))

#Insert a single document
str <- c('{"hello" : "Amazon DocumentDB"}')
client$insert(str)

#Find the document that was previously written
client$find()
```

------
#### [ Ruby ]

以下代码说明了如何在启用了 TLS 的情况下使用 Ruby 连接到 Amazon DocumentDB。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

```
require 'mongo'
require 'neatjson'
require 'json'
client_host = 'mongodb://sample-cluster.node.cn-north-1.docdb.amazonaws.com:27017'
client_options = {
   database: 'test',
   replica_set: 'rs0',
   read: {:secondary_preferred => 1},
   user: 'sample-user',
   password: 'password',
   ssl: true,
   ssl_verify: true,
   ssl_ca_cert: 'PATH/rds-combined-ca-bundle.pem',
   retry_writes: false
}

begin
   ##Create a MongoDB client, open a connection to Amazon DocumentDB as a
   ##   replica set and specify the read preference as secondary preferred
   client = Mongo::Client.new(client_host, client_options)
   
   ##Insert a single document
   x = client[:test].insert_one({"hello":"Amazon DocumentDB"})
   
   ##Find the document that was previously written
   result = client[:test].find()
   
   #Print the document
   result.each do |document|
      puts JSON.neat_generate(document)
   end
end

#Close the connection
client.close
```

------

## 禁用了 TLS 的情况下的连接


要查看以编程方式连接到禁用了 TLS 的 Amazon DocumentDB 集群的代码示例，请选择您要使用的语言所对应的选项卡。

------
#### [ Python ]

以下代码说明了如何在禁用 TLS 的情况下使用 Python 连接到 Amazon DocumentDB。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

```
## Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set and specify the read preference as secondary preferred 
                    
import pymongo
import sys

client = pymongo.MongoClient('mongodb://sample-user:password@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/?replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')

##Specify the database to be used
db = client.sample_database

##Specify the collection to be used
col = db.sample_collection

##Insert a single document
col.insert_one({'hello':'Amazon DocumentDB'})

##Find the document that was previously written
x = col.find_one({'hello':'Amazon DocumentDB'})

##Print the result to the screen
print(x)

##Close the connection
client.close()
```

------
#### [ Node.js ]

以下代码说明了如何在禁用了 TLS 的情况下使用 Node.js 连接到 Amazon DocumentDB。

**重要**  
低于版本 6.13.1 的 Node.js 驱动程序存在已知限制，Amazon DocumentDB 目前不支持用这种驱动程序进行 IAM 身份验证。必须升级 Node.js 驱动程序以及使用 Node.js 驱动程序的工具（例如 mongosh），以使用 Node.js 驱动程序版本 6.13.1 或更高版本。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

```
var MongoClient = require('mongodb').MongoClient;
                  
//Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set,
//  and specify the read preference as secondary preferred
var client = MongoClient.connect(
'mongodb://sample-user:password@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/sample-database?replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false', 
{ 
  useNewUrlParser: true
},

function(err, client) {
    if(err)
        throw err;
    //Specify the database to be used
    db = client.db('sample-database');
    
    //Specify the collection to be used
    col = db.collection('sample-collection');

    //Insert a single document
    col.insertOne({'hello':'Amazon DocumentDB'}, function(err, result){
      //Find the document that was previously written
      col.findOne({'hello':'Amazon DocumentDB'}, function(err, result){
        //Print the result to the screen
        console.log(result);
        
        //Close the connection
        client.close()
      });
   });
});
```

------
#### [ PHP ]

以下代码说明了如何在禁用了 TLS 的情况下使用 PHP 连接到 Amazon DocumentDB。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

```
<?php
//Include Composer's autoloader
require 'vendor/autoload.php';

//Create a MongoDB client and open connection to Amazon DocumentDB
$client = new MongoDB\Client("mongodb://sample-user:password@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/?retryWrites=false");

//Specify the database and collection to be used
$col = $client->sampledatabase->samplecollection;

//Insert a single document
$result = $col->insertOne( [ 'hello' => 'Amazon DocumentDB'] );

//Find the document that was previously written
$result = $col->findOne(array('hello' => 'Amazon DocumentDB'));

//Print the result to the screen
print_r($result);
?>
```

------
#### [ Go ]

以下代码说明了如何在禁用了 TLS 的情况下使用 Go 连接到 Amazon DocumentDB。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

```
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

const (
	// Timeout operations after N seconds
	connectTimeout  = 5
	queryTimeout    = 30
	username        = "sample-user"
	password        = "password"
	clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017"
	
	// Which instances to read from
	readPreference           = "secondaryPreferred"
	connectionStringTemplate = "mongodb://%s:%s@%s/sample-database?replicaSet=rs0&readpreference=%s"
)

func main() {

	connectionURI := fmt.Sprintf(connectionStringTemplate, username, password, clusterEndpoint, readPreference)

	client, err := mongo.NewClient(options.Client().ApplyURI(connectionURI))
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), connectTimeout*time.Second)
	defer cancel()

	err = client.Connect(ctx)
	if err != nil {
		log.Fatalf("Failed to connect to cluster: %v", err)
	}

	// Force a connection to verify our connection string
	err = client.Ping(ctx, nil)
	if err != nil {
		log.Fatalf("Failed to ping cluster: %v", err)
	}

	fmt.Println("Connected to DocumentDB!")

	collection := client.Database("sample-database").Collection("sample-collection")

	ctx, cancel = context.WithTimeout(context.Background(), queryTimeout*time.Second)
	defer cancel()

	res, err := collection.InsertOne(ctx, bson.M{"name": "pi", "value": 3.14159})
	if err != nil {
		log.Fatalf("Failed to insert document: %v", err)
	}

	id := res.InsertedID
	log.Printf("Inserted document ID: %s", id)

	ctx, cancel = context.WithTimeout(context.Background(), queryTimeout*time.Second)
	defer cancel()

	cur, err := collection.Find(ctx, bson.D{})

	if err != nil {
		log.Fatalf("Failed to run find query: %v", err)
	}
	defer cur.Close(ctx)

	for cur.Next(ctx) {
		var result bson.M
		err := cur.Decode(&result)
		log.Printf("Returned: %v", result)

		if err != nil {
			log.Fatal(err)
		}
	}

	if err := cur.Err(); err != nil {
		log.Fatal(err)
	}

}
```

------
#### [ Java ]

以下代码说明了如何在禁用了 TLS 的情况下使用 Java 连接到 Amazon DocumentDB。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

```
package com.example.documentdb;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.ServerAddress;
import com.mongodb.MongoException;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import org.bson.Document;


public final class Main {
    private Main() {
    }
    public static void main(String[] args) {

        String template = "mongodb://%s:%s@%s/sample-database?replicaSet=rs0&readpreference=%s";
        String username = "sample-user";
        String password = "password";
        String clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
        String readPreference = "secondaryPreferred";
        String connectionString = String.format(template, username, password, clusterEndpoint, readPreference);

        MongoClientURI clientURI = new MongoClientURI(connectionString);
        MongoClient mongoClient = new MongoClient(clientURI);

        MongoDatabase testDB = mongoClient.getDatabase("sample-database");
        MongoCollection<Document> numbersCollection = testDB.getCollection("sample-collection");

        Document doc = new Document("name", "pi").append("value", 3.14159);
        numbersCollection.insertOne(doc);

        MongoCursor<Document> cursor = numbersCollection.find().iterator();
        try {
            while (cursor.hasNext()) {
                System.out.println(cursor.next().toJson());
            }
        } finally {
            cursor.close();
        }

    }
}
```

------
#### [ C\$1 / .NET ]

以下代码说明了如何在禁用了 TLS 的情况下使用 C\$1 / .NET 连接到 Amazon DocumentDB。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

```
using System;
using System.Text;
using System.Linq;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using MongoDB.Driver;
using MongoDB.Bson;

namespace CSharpSample
{
   class Program
    {
       static void Main(string[] args)
        {
           string template = "mongodb://{0}:{1}@{2}/sampledatabase?replicaSet=rs0&readpreference={3}";
           string username = "sample-user";
           string password = "password";
           string clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
           string readPreference = "secondaryPreferred";
           string connectionString = String.Format(template, username, password, clusterEndpoint, readPreference);

           var settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
           var client = new MongoClient(settings);

           var database = client.GetDatabase("sampledatabase");
           var collection = database.GetCollection<BsonDocument>("samplecollection");
           var docToInsert = new BsonDocument { { "pi", 3.14159 } };
            collection.InsertOne(docToInsert);
        }
    }
}
```

------
#### [ MongoDB Shell ]

以下代码演示了如何在禁用 TLS 的情况下，使用最新版本 mongosh 或先前的 mongo Shell 版本连接和查询 Amazon DocumentDB。

**使用 mongosh 连接到 Amazon DocumentDB**

**重要**  
低于版本 6.13.1 的 Node.js 驱动程序存在已知限制，Amazon DocumentDB 目前不支持用这种驱动程序进行 IAM 身份验证。必须升级 Node.js 驱动程序以及使用 Node.js 驱动程序的工具（例如 mongosh），以使用 Node.js 驱动程序版本 6.13.1 或更高版本。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

**使用先前的 mongo Shell 版本连接到 Amazon DocumentDB**

如果您使用 IAM，则必须使用先前版本的 mongo Shell。输入以下命令选项之一：

```
mongo --host cluster-end-point:27017 --username sample-user --password password
```

如果您使用的版本等于或高于 4.2，请使用以下代码进行连接。Amazon DocumentDB 不支持可重试写入。如果您使用旧版 mongo Shell（而非 mongosh），不要在任何代码字符串中包含 `retryWrites=false` 命令。默认情况下，禁用可重试写入。包含 `retryWrites=false` 可能导致正常读取命令失败。

```
mongo --host cluster-end-point:27017 --username sample-user --password password
```

**测试连接**

1. 插入单个文档。

   ```
   db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
   ```

1. 查找以前插入的文档。

   ```
   db.myTestCollection.find({'hello':'Amazon DocumentDB'})
   ```

------
#### [ R ]

以下代码说明了如何在禁用了 TLS 的情况下使用 mongolite ([https://jeroen.github.io/mongolite/](https://jeroen.github.io/mongolite/)) 通过 R 连接到 Amazon DocumentDB。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

```
#Include the mongolite library.
library(mongolite)
               
#Create a MongoDB client, open a connection to Amazon DocumentDB as a replica
#   set and specify the read preference as secondary preferred
client <- mongo(url = "mongodb://sample-user:password@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/sample-database?readPreference=secondaryPreferred&replicaSet=rs0")

##Insert a single document
str <- c('{"hello" : "Amazon DocumentDB"}')
client$insert(str)

##Find the document that was previously written
client$find()
```

------
#### [ Ruby ]

以下代码说明了如何在禁用了 TLS 的情况下使用 Ruby 连接到 Amazon DocumentDB。

在以下示例中，将每个 *user input placeholder* 替换为您的集群信息。

```
require 'mongo'
require 'neatjson'
require 'json'
client_host = 'mongodb://sample-cluster.node.us-east-1.docdb.amazonaws.com:27017'
client_options = {
   database: 'test',
   replica_set: 'rs0',
   read: {:secondary_preferred => 1},
   user: 'sample-user',
   password: 'password',
   ssl: true,
   ssl_verify: true,
   ssl_ca_cert: 'PATH/rds-combined-ca-bundle.pem',
   retry_writes: false
}
               
begin
   ##Create a MongoDB client, open a connection to Amazon DocumentDB as a
   ##   replica set and specify the read preference as secondary preferred
   client = Mongo::Client.new(client_host, client_options)
   
   ##Insert a single document
   x = client[:test].insert_one({"hello":"Amazon DocumentDB"})
   
   ##Find the document that was previously written
   result = client[:test].find()
   
   #Print the document
   result.each do |document|
      puts JSON.neat_generate(document)
   end
end

#Close the connection
client.close
```

------