通过编程方式连接到 Amazon DocumentDB

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

如果您尝试从集群所在的 VPC 外部连接到 Amazon DocumentDB,请参阅从 Amazon VPC 外部连接到 Amazon DocumentDB集群

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

确定 tls 参数的值

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

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

    1. 通过以下网址登录 AWS 管理控制台并打开 Amazon DocumentDB 控制台:https://console.aws.amazon.com/docdb

    2. 在左侧导航窗格中,选择集群

    3. 在集群列表中,选择您的集群的名称。

    4. 生成的页面将显示所选集群的详细信息。向下滚动到 Cluster details (集群详细信息)。在此部分的底部,在 Cluster parameter group (集群参数组) 的下方找到参数组的名称。

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

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

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

    1. [
    2. [
    3. "sample-cluster",
    4. "sample-parameter-group"
    5. ]
    6. ]
  2. 确定集群参数组中 tls 参数的值。

    1. 在导航窗格中,选择参数组

    2. Cluster parameter groups (集群参数组) 窗口中,选择您的集群参数组。

    3. 打开的页面上会显示您的集群参数组中包含的参数。您可以在其中查看 tls 参数的值。有关修改此参数的信息,请参阅修改 Amazon DocumentDB 集群参数组

    您可以使用 describe-db-cluster-parameters AWS CLI 命令来查看集群参数组中的参数的详细信息。

    • --describe-db-cluster-parameters — 列出参数组中的所有参数及其值。

      • --db-cluster-parameter-group name — 必需。您的集群参数组的名称。
  1. <pre><code>aws docdb describe-db-cluster-parameters \
  2. --db-cluster-parameter-group-name sample-parameter-group</code></pre>
  3. 此操作的输出将类似于以下内容:
  4. <pre><div></div><code>{
  5. "Parameters": [
  6. {
  7. "ParameterName": "profiler_threshold_ms",
  8. "ParameterValue": "100",
  9. "Description": "Operations longer than profiler_threshold_ms will be logged",
  10. "Source": "system",
  11. "ApplyType": "dynamic",
  12. "DataType": "integer",
  13. "AllowedValues": "50-2147483646",
  14. "IsModifiable": true,
  15. "ApplyMethod": "pending-reboot"
  16. },
  17. {
  18. "<b>ParameterName": "tls"</b>,
  19. "ParameterValue": "disabled",
  20. "Description": "Config to enable/disable TLS",
  21. "Source": "user",
  22. "ApplyType": "static",
  23. "DataType": "string",
  24. "AllowedValues": "disabled,enabled",
  25. "IsModifiable": true,
  26. "ApplyMethod": "pending-reboot"
  27. }
  28. ]
  29. }</code></pre>

确定 tls 参数的值后,即可使用以下部分中的代码示例之一继续连接到您的集群。

启用了 TLS 的情况下的连接

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

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

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

Python

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

  1. import pymongo
  2. import sys
  3. ##Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set and specify the read preference as secondary preferred
  4. client = pymongo.MongoClient('mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/?ssl=true&ssl_ca_certs=rds-combined-ca-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred')
  5. ##Specify the database to be used
  6. db = client.sample_database
  7. ##Specify the collection to be used
  8. col = db.sample_collection
  9. ##Insert a single document
  10. col.insert_one({'hello':'Amazon DocumentDB'})
  11. ##Find the document that was previously written
  12. x = col.find_one({'hello':'Amazon DocumentDB'})
  13. ##Print the result to the screen
  14. print(x)
  15. ##Close the connection
  16. client.close()

Node.js

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

  1. var MongoClient = require('mongodb').MongoClient,
  2. f = require('util').format,
  3. fs = require('fs');
  4. //Specify the Amazon DocumentDB cert
  5. var ca = [fs.readFileSync("rds-combined-ca-bundle.pem")];
  6. //Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set,
  7. // and specify the read preference as secondary preferred
  8. var client = MongoClient.connect(
  9. 'mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/sample-database?ssl=true&replicaSet=rs0&readPreference=secondaryPreferred',
  10. {
  11. sslValidate: true,
  12. sslCA:ca,
  13. useNewUrlParser: true
  14. },
  15. function(err, client) {
  16. if(err)
  17. throw err;
  18. //Specify the database to be used
  19. db = client.db('sample-database');
  20. //Specify the collection to be used
  21. col = db.collection('sample-collection');
  22. //Insert a single document
  23. col.insertOne({'hello':'Amazon DocumentDB'}, function(err, result){
  24. //Find the document that was previously written
  25. col.findOne({'hello':'Amazon DocumentDB'}, function(err, result){
  26. //Print the result to the screen
  27. console.log(result);
  28. //Close the connection
  29. client.close()
  30. });
  31. });
  32. });

PHP

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

  1. <?php
  2. //Include Composer's autoloader
  3. require 'vendor/autoload.php';
  4. $SSL_DIR = "/home/ubuntu";
  5. $SSL_FILE = "rds-combined-ca-bundle.pem";
  6. //Specify the Amazon DocumentDB cert
  7. $ctx = stream_context_create(array(
  8. "ssl" => array(
  9. "cafile" => $SSL_DIR . "/" . $SSL_FILE,
  10. ))
  11. );
  12. //Create a MongoDB client and open connection to Amazon DocumentDB
  13. $client = new MongoDB\Client("mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017", array("ssl" => true), array("context" => $ctx));
  14. //Specify the database and collection to be used
  15. $col = $client->sample-database->sample-collection;
  16. //Insert a single document
  17. $result = $col->insertOne( [ 'hello' => 'Amazon DocumentDB'] );
  18. //Find the document that was previously written
  19. $result = $col->findOne(array('hello' => 'Amazon DocumentDB'));
  20. //Print the result to the screen
  21. print_r($result);
  22. ?>

Go

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

注意

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

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "time"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/mongo"
  9. "go.mongodb.org/mongo-driver/mongo/options"
  10. "io/ioutil"
  11. "crypto/tls"
  12. "crypto/x509"
  13. "errors"
  14. )
  15. const (
  16. // Path to the AWS CA file
  17. caFilePath = "rds-combined-ca-bundle.pem"
  18. // Timeout operations after N seconds
  19. connectTimeout = 5
  20. queryTimeout = 30
  21. username = "<sample-user>"
  22. password = "<password>"
  23. clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017"
  24. // Which instances to read from
  25. readPreference = "secondaryPreferred"
  26. connectionStringTemplate = "mongodb://%s:%s@%s/sample-database?ssl=true&replicaSet=rs0&readpreference=%s"
  27. )
  28. func main() {
  29. connectionURI := fmt.Sprintf(connectionStringTemplate, username, password, clusterEndpoint, readPreference)
  30. tlsConfig, err := getCustomTLSConfig(caFilePath)
  31. if err != nil {
  32. log.Fatalf("Failed getting TLS configuration: %v", err)
  33. }
  34. client, err := mongo.NewClient(options.Client().ApplyURI(connectionURI).SetTLSConfig(tlsConfig))
  35. if err != nil {
  36. log.Fatalf("Failed to create client: %v", err)
  37. }
  38. ctx, cancel := context.WithTimeout(context.Background(), connectTimeout*time.Second)
  39. defer cancel()
  40. err = client.Connect(ctx)
  41. if err != nil {
  42. log.Fatalf("Failed to connect to cluster: %v", err)
  43. }
  44. // Force a connection to verify our connection string
  45. err = client.Ping(ctx, nil)
  46. if err != nil {
  47. log.Fatalf("Failed to ping cluster: %v", err)
  48. }
  49. fmt.Println("Connected to DocumentDB!")
  50. collection := client.Database("sample-database").Collection("sample-collection")
  51. ctx, cancel = context.WithTimeout(context.Background(), queryTimeout*time.Second)
  52. defer cancel()
  53. res, err := collection.InsertOne(ctx, bson.M{"name": "pi", "value": 3.14159})
  54. if err != nil {
  55. log.Fatalf("Failed to insert document: %v", err)
  56. }
  57. id := res.InsertedID
  58. log.Printf("Inserted document ID: %s", id)
  59. ctx, cancel = context.WithTimeout(context.Background(), queryTimeout*time.Second)
  60. defer cancel()
  61. cur, err := collection.Find(ctx, bson.D{})
  62. if err != nil {
  63. log.Fatalf("Failed to run find query: %v", err)
  64. }
  65. defer cur.Close(ctx)
  66. for cur.Next(ctx) {
  67. var result bson.M
  68. err := cur.Decode(&result)
  69. log.Printf("Returned: %v", result)
  70. if err != nil {
  71. log.Fatal(err)
  72. }
  73. }
  74. if err := cur.Err(); err != nil {
  75. log.Fatal(err)
  76. }
  77. }
  78. func getCustomTLSConfig(caFile string) (*tls.Config, error) {
  79. tlsConfig := new(tls.Config)
  80. certs, err := ioutil.ReadFile(caFile)
  81. if err != nil {
  82. return tlsConfig, err
  83. }
  84. tlsConfig.RootCAs = x509.NewCertPool()
  85. ok := tlsConfig.RootCAs.AppendCertsFromPEM(certs)
  86. if !ok {
  87. return tlsConfig, errors.New("Failed parsing pem file")
  88. }
  89. return tlsConfig, nil
  90. }

Java

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

  1. 从 Amazon RDS https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem 下载 CA 文件。

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

    下面是一个示例 Shell 脚本,它将证书捆绑包导入 Linux 操作系统上的信任存储。

    1. mydir=/tmp/certs
    2. truststore=${mydir}/rds-truststore.jks
    3. storepassword=<truststorePassword>
    4. curl -sS "https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem" > ${mydir}/rds-combined-ca-bundle.pem
    5. awk 'split_after == 1 {n++;split_after=0} /-----END CERTIFICATE-----/ {split_after=1}{print > "rds-ca-" n ".pem"}' < ${mydir}/rds-combined-ca-bundle.pem
    6. for CERT in rds-ca-*; do
    7. alias=$(openssl x509 -noout -text -in $CERT | perl -ne 'next unless /Subject:/; s/.*(CN=|CN = )//; print')
    8. echo "Importing $alias"
    9. keytool -import -file ${CERT} -alias "${alias}" -storepass ${storepassword} -keystore ${truststore} -noprompt
    10. rm $CERT
    11. done
    12. rm ${mydir}/rds-combined-ca-bundle.pem
    13. echo "Trust store content is: "
    14. keytool -list -v -keystore "$truststore" -storepass ${storepassword} | grep Alias | cut -d " " -f3- | while read alias
    15. do
    16. expiry=`keytool -list -v -keystore "$truststore" -storepass ${storepassword} -alias "${alias}" | grep Valid | perl -ne 'if(/until: (.*?)\n/) { print "$1\n"; }'`
    17. echo " Certificate ${alias} expires in '$expiry'"
    18. done

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

    1. mydir=/tmp/certs
    2. truststore=${mydir}/rds-truststore.jks
    3. storepassword=<truststorePassword>
    4. curl -sS "https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem" > ${mydir}/rds-combined-ca-bundle.pem
    5. split -p "-----BEGIN CERTIFICATE-----" ${mydir}/rds-combined-ca-bundle.pem rds-ca-
    6. for CERT in rds-ca-*; do
    7. alias=$(openssl x509 -noout -text -in $CERT | perl -ne 'next unless /Subject:/; s/.*(CN=|CN = )//; print')
    8. echo "Importing $alias"
    9. keytool -import -file ${CERT} -alias "${alias}" -storepass ${storepassword} -keystore ${truststore} -noprompt
    10. rm $CERT
    11. done
    12. rm ${mydir}/rds-combined-ca-bundle.pem
    13. echo "Trust store content is: "
    14. keytool -list -v -keystore "$truststore" -storepass ${storepassword} | grep Alias | cut -d " " -f3- | while read alias
    15. do
    16. expiry=`keytool -list -v -keystore "$truststore" -storepass ${storepassword} -alias "${alias}" | grep Valid | perl -ne 'if(/until: (.*?)\n/) { print "$1\n"; }'`
    17. echo " Certificate ${alias} expires in '$expiry'"
    18. done
  3. 请先在您的应用程序中设置以下系统属性,以便在该程序中使用 keystore,然后再连接到 Amazon DocumentDB 集群。

    1. javax.net.ssl.trustStore: <truststore>
    2. javax.net.ssl.trustStorePassword: <truststorePassword>
  4. 以下代码说明了如何在启用了 TLS 的情况下使用 Java 连接到 Amazon DocumentDB。

    1. package com.example.documentdb;
    2. import com.mongodb.MongoClient;
    3. import com.mongodb.MongoClientURI;
    4. import com.mongodb.ServerAddress;
    5. import com.mongodb.MongoException;
    6. import com.mongodb.client.MongoCursor;
    7. import com.mongodb.client.MongoDatabase;
    8. import com.mongodb.client.MongoCollection;
    9. import org.bson.Document;
    10. public final class Main {
    11. private Main() {
    12. }
    13. public static void main(String[] args) {
    14. String template = "mongodb://%s:%s@%s/sample-database?ssl=true&replicaSet=rs0&readpreference=%s";
    15. String username = "<sample-user>";
    16. String password = "<password>";
    17. String clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
    18. String readPreference = "secondaryPreferred";
    19. String connectionString = String.format(template, username, password, clusterEndpoint, readPreference);
    20. String truststore = "<truststore>";
    21. String truststorePassword = "<truststorePassword>";
    22. System.setProperty("javax.net.ssl.trustStore", truststore);
    23. System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
    24. MongoClientURI clientURI = new MongoClientURI(connectionString);
    25. MongoClient mongoClient = new MongoClient(clientURI);
    26. MongoDatabase testDB = mongoClient.getDatabase("sample-database");
    27. MongoCollection<Document> numbersCollection = testDB.getCollection("sample-collection");
    28. Document doc = new Document("name", "pi").append("value", 3.14159);
    29. numbersCollection.insertOne(doc);
    30. MongoCursor<Document> cursor = numbersCollection.find().iterator();
    31. try {
    32. while (cursor.hasNext()) {
    33. System.out.println(cursor.next().toJson());
    34. }
    35. } finally {
    36. cursor.close();
    37. }
    38. }
    39. }

C# / .NET

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

  1. using System;
  2. using System.Text;
  3. using System.Linq;
  4. using System.Collections.Generic;
  5. using System.Security.Cryptography;
  6. using System.Security.Cryptography.X509Certificates;
  7. using System.Net.Security;
  8. using MongoDB.Driver;
  9. using MongoDB.Bson;
  10. namespace DocDB
  11. {
  12. class Program
  13. {
  14. static void Main(string[] args)
  15. {
  16. string template = "mongodb://{0}:{1}@{2}/sample-database?ssl=true&replicaSet=rs0&readpreference={3}";
  17. string username = "<sample-user>";
  18. string password = "<password>";
  19. string readPreference = "secondaryPreferred";
  20. string clusterEndpoint="sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
  21. string connectionString = String.Format(template, username, password, clusterEndpoint, readPreference);
  22. string pathToCAFile = "<path_to_rds-combined-ca-bundle.p7b_file>";
  23. // ADD CA certificate to local trust store
  24. // DO this once - Maybe when your service starts
  25. X509Store localTrustStore = new X509Store(StoreName.Root);
  26. X509Certificate2Collection certificateCollection = new X509Certificate2Collection();
  27. certificateCollection.Import(pathToCAFile);
  28. try
  29. {
  30. localTrustStore.Open(OpenFlags.ReadWrite);
  31. localTrustStore.AddRange(certificateCollection);
  32. }
  33. catch (Exception ex)
  34. {
  35. Console.WriteLine("Root certificate import failed: " + ex.Message);
  36. throw;
  37. }
  38. finally
  39. {
  40. localTrustStore.Close();
  41. }
  42. var settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
  43. var client = new MongoClient(settings);
  44. var database = client.GetDatabase("sample-database");
  45. var collection = database.GetCollection<BsonDocument>("sample-collection");
  46. var docToInsert = new BsonDocument { { "pi", 3.14159 } };
  47. collection.InsertOne(docToInsert);
  48. }
  49. }
  50. }

mongo shell

以下代码说明了如何在启用了 TLS 的情况下使用 mongo shell 连接和查询 Amazon DocumentDB。

  1. 使用 mongo shell 连接到 Amazon DocumentDB。

    1. mongo --ssl --host sample-cluster.node.us-east-1.docdb.amazonaws.com:27017 --sslCAFile rds-combined-ca-bundle.pem --username <sample-user> --password <password>
  2. 插入单个文档。

    1. db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
  3. 查找以前插入的文档。

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

R

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

  1. #Include the mongolite library.
  2. library(mongolite)
  3. mongourl <- paste("mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/test2?ssl=true&",
  4. "readPreference=secondaryPreferred&replicaSet=rs0", sep="")
  5. #Create a MongoDB client, open a connection to Amazon DocumentDB as a replica
  6. # set and specify the read preference as secondary preferred
  7. client <- mongo(url = mongo(url = mongourl, options = ssl_options(weak_cert_validation = F, ca = <path to 'rds-combined-ca-bundle.pem'>))
  8. #Insert a single document
  9. str <- c('{"hello" : "Amazon DocumentDB"}')
  10. client$insert(str)
  11. #Find the document that was previously written
  12. client$find()

Ruby

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

  1. require 'mongo'
  2. require 'neatjson'
  3. require 'json'
  4. client_host = 'mongodb://sample-cluster.node.us-east-1.docdb.amazonaws.com:27017'
  5. client_options = {
  6. database: 'test',
  7. replica_set: 'rs0',
  8. read: {:secondary_preferred => 1},
  9. user: '<sample-user>',
  10. password: '<password>',
  11. ssl: true,
  12. ssl_verify: true,
  13. ssl_ca_cert: <path to 'rds-combined-ca-bundle.pem'>
  14. }
  15. begin
  16. ##Create a MongoDB client, open a connection to Amazon DocumentDB as a
  17. ## replica set and specify the read preference as secondary preferred
  18. client = Mongo::Client.new(client_host, client_options)
  19. ##Insert a single document
  20. x = client[:test].insert_one({"hello":"Amazon DocumentDB"})
  21. ##Find the document that was previously written
  22. result = client[:test].find()
  23. #Print the document
  24. result.each do |document|
  25. puts JSON.neat_generate(document)
  26. end
  27. end
  28. #Close the connection
  29. client.close

禁用了 TLS 的情况下的连接

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

Python

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

  1. ## Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set and specify the read preference as secondary preferred
  2. client = pymongo.MongoClient('mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/?replicaSet=rs0&readPreference=secondaryPreferred')
  3. ##Specify the database to be used
  4. db = client.sample_database
  5. ##Specify the collection to be used
  6. col = db.sample_collection
  7. ##Insert a single document
  8. col.insert_one({'hello':'Amazon DocumentDB'})
  9. ##Find the document that was previously written
  10. x = col.find_one({'hello':'Amazon DocumentDB'})
  11. ##Print the result to the screen
  12. print(x)
  13. ##Close the connection
  14. client.close()

Node.js

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

  1. var MongoClient = require('mongodb').MongoClient;
  2. //Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set,
  3. // and specify the read preference as secondary preferred
  4. var client = MongoClient.connect(
  5. 'mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/sample-database?replicaSet=rs0&readPreference=secondaryPreferred',
  6. {
  7. useNewUrlParser: true
  8. },
  9. function(err, client) {
  10. if(err)
  11. throw err;
  12. //Specify the database to be used
  13. db = client.db('sample-database');
  14. //Specify the collection to be used
  15. col = db.collection('sample-collection');
  16. //Insert a single document
  17. col.insertOne({'hello':'Amazon DocumentDB'}, function(err, result){
  18. //Find the document that was previously written
  19. col.findOne({'hello':'Amazon DocumentDB'}, function(err, result){
  20. //Print the result to the screen
  21. console.log(result);
  22. //Close the connection
  23. client.close()
  24. });
  25. });
  26. });

PHP

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

  1. <?php
  2. //Include Composer's autoloader
  3. require 'vendor/autoload.php';
  4. //Create a MongoDB client and open connection to Amazon DocumentDB
  5. $client = new MongoDB\Client("mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017");
  6. //Specify the database and collection to be used
  7. $col = $client->sample-database->sample-collection;
  8. //Insert a single document
  9. $result = $col->insertOne( [ 'hello' => 'Amazon DocumentDB'] );
  10. //Find the document that was previously written
  11. $result = $col->findOne(array('hello' => 'Amazon DocumentDB'));
  12. //Print the result to the screen
  13. print_r($result);
  14. ?>

Go

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

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "time"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/mongo"
  9. "go.mongodb.org/mongo-driver/mongo/options"
  10. )
  11. const (
  12. // Timeout operations after N seconds
  13. connectTimeout = 5
  14. queryTimeout = 30
  15. username = "<sample-user>"
  16. password = "<password>"
  17. clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017"
  18. // Which instances to read from
  19. readPreference = "secondaryPreferred"
  20. connectionStringTemplate = "mongodb://%s:%s@%s/sample-database?replicaSet=rs0&readpreference=%s"
  21. )
  22. func main() {
  23. connectionURI := fmt.Sprintf(connectionStringTemplate, username, password, clusterEndpoint, readPreference)
  24. client, err := mongo.NewClient(options.Client().ApplyURI(connectionURI))
  25. if err != nil {
  26. log.Fatalf("Failed to create client: %v", err)
  27. }
  28. ctx, cancel := context.WithTimeout(context.Background(), connectTimeout*time.Second)
  29. defer cancel()
  30. err = client.Connect(ctx)
  31. if err != nil {
  32. log.Fatalf("Failed to connect to cluster: %v", err)
  33. }
  34. // Force a connection to verify our connection string
  35. err = client.Ping(ctx, nil)
  36. if err != nil {
  37. log.Fatalf("Failed to ping cluster: %v", err)
  38. }
  39. fmt.Println("Connected to DocumentDB!")
  40. collection := client.Database("sample-database").Collection("sample-collection")
  41. ctx, cancel = context.WithTimeout(context.Background(), queryTimeout*time.Second)
  42. defer cancel()
  43. res, err := collection.InsertOne(ctx, bson.M{"name": "pi", "value": 3.14159})
  44. if err != nil {
  45. log.Fatalf("Failed to insert document: %v", err)
  46. }
  47. id := res.InsertedID
  48. log.Printf("Inserted document ID: %s", id)
  49. ctx, cancel = context.WithTimeout(context.Background(), queryTimeout*time.Second)
  50. defer cancel()
  51. cur, err := collection.Find(ctx, bson.D{})
  52. if err != nil {
  53. log.Fatalf("Failed to run find query: %v", err)
  54. }
  55. defer cur.Close(ctx)
  56. for cur.Next(ctx) {
  57. var result bson.M
  58. err := cur.Decode(&result)
  59. log.Printf("Returned: %v", result)
  60. if err != nil {
  61. log.Fatal(err)
  62. }
  63. }
  64. if err := cur.Err(); err != nil {
  65. log.Fatal(err)
  66. }
  67. }

Java

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

  1. package com.example.documentdb;
  2. import com.mongodb.MongoClient;
  3. import com.mongodb.MongoClientURI;
  4. import com.mongodb.ServerAddress;
  5. import com.mongodb.MongoException;
  6. import com.mongodb.client.MongoCursor;
  7. import com.mongodb.client.MongoDatabase;
  8. import com.mongodb.client.MongoCollection;
  9. import org.bson.Document;
  10. public final class Main {
  11. private Main() {
  12. }
  13. public static void main(String[] args) {
  14. String template = "mongodb://%s:%s@%s/sample-database?replicaSet=rs0&readpreference=%s";
  15. String username = "<sample-user>";
  16. String password = "<password>";
  17. String clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
  18. String readPreference = "secondaryPreferred";
  19. String connectionString = String.format(template, username, password, clusterEndpoint, readPreference);
  20. MongoClientURI clientURI = new MongoClientURI(connectionString);
  21. MongoClient mongoClient = new MongoClient(clientURI);
  22. MongoDatabase testDB = mongoClient.getDatabase("sample-database");
  23. MongoCollection<Document> numbersCollection = testDB.getCollection("sample-collection");
  24. Document doc = new Document("name", "pi").append("value", 3.14159);
  25. numbersCollection.insertOne(doc);
  26. MongoCursor<Document> cursor = numbersCollection.find().iterator();
  27. try {
  28. while (cursor.hasNext()) {
  29. System.out.println(cursor.next().toJson());
  30. }
  31. } finally {
  32. cursor.close();
  33. }
  34. }
  35. }

C# / .NET

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

  1. using System;
  2. using System.Text;
  3. using System.Linq;
  4. using System.Collections.Generic;
  5. using System.Security.Cryptography;
  6. using System.Security.Cryptography.X509Certificates;
  7. using System.Net.Security;
  8. using MongoDB.Driver;
  9. using MongoDB.Bson;
  10. namespace CSharpSample
  11. {
  12. class Program
  13. {
  14. static void Main(string[] args)
  15. {
  16. string template = "mongodb://{0}:{1}@{2}/sample-database?&replicaSet=rs0&readpreference={3}";
  17. string username = "<sample-user>";
  18. string password = "<password>";
  19. string clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
  20. string readPreference = "secondaryPreferred";
  21. string connectionString = String.Format(template, username, password, clusterEndpoint, readPreference);
  22. var settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
  23. var client = new MongoClient(settings);
  24. var database = client.GetDatabase("sample-database");
  25. var collection = database.GetCollection<BsonDocument>("sample-collection");
  26. var docToInsert = new BsonDocument { { "pi", 3.14159 } };
  27. collection.InsertOne(docToInsert);
  28. }
  29. }
  30. }

mongo shell

以下代码演示如何在禁用 TLS 时使用 mongo shell 连接和查询 Amazon DocumentDB。

  1. 使用 mongo shell 连接到 Amazon DocumentDB。

    1. mongo --host mycluster.node.us-east-1.docdb.amazonaws.com:27017 --username <sample-user> --password <password>
  2. 插入单个文档。

    1. db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
  3. 查找以前插入的文档。

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

R

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

  1. #Include the mongolite library.
  2. library(mongolite)
  3. #Create a MongoDB client, open a connection to Amazon DocumentDB as a replica
  4. # set and specify the read preference as secondary preferred
  5. client <- mongo(url = "mongodb://sample-user;:password@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/sample-database?readPreference=secondaryPreferred&replicaSet=rs0")
  6. ##Insert a single document
  7. str <- c('{"hello" : "Amazon DocumentDB"}')
  8. client$insert(str)
  9. ##Find the document that was previously written
  10. client$find()

Ruby

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

  1. require 'mongo'
  2. require 'neatjson'
  3. require 'json'
  4. client_host = 'mongodb://sample-cluster.node.us-east-1.docdb.amazonaws.com:27017'
  5. client_options = {
  6. database: 'test',
  7. replica_set: 'rs0',
  8. read: {:secondary_preferred => 1},
  9. user: '<sample-user>',
  10. password: '<password>',
  11. ssl: true,
  12. ssl_verify: true,
  13. ssl_ca_cert: <path to 'rds-combined-ca-bundle.pem'>
  14. }
  15. begin
  16. ##Create a MongoDB client, open a connection to Amazon DocumentDB as a
  17. ## replica set and specify the read preference as secondary preferred
  18. client = Mongo::Client.new(client_host, client_options)
  19. ##Insert a single document
  20. x = client[:test].insert_one({"hello":"Amazon DocumentDB"})
  21. ##Find the document that was previously written
  22. result = client[:test].find()
  23. #Print the document
  24. result.each do |document|
  25. puts JSON.neat_generate(document)
  26. end
  27. end
  28. #Close the connection
  29. client.close