以编程方式连接到亚马逊 DocumentDB - Amazon DocumentDB

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

以编程方式连接到亚马逊 DocumentDB

本部分包含说明了如何使用多种不同语言连接到 Amazon DocumentDB(与 MongoDB 兼容)的代码示例。根据您连接的集群是启用还是禁用了传输层安全 (TLS),这些示例分为两部分。默认情况下,在亚马逊文档数据库集群上TLS处于启用状态。但是,TLS如果你愿意,你可以关闭。有关更多信息,请参阅 加密传输中数据

如果您尝试从集群所在的外部连接到您的 Amazon DocumentDB,请参阅。VPC 从亚马逊外部连接到亚马逊文档数据库集群 VPC

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

确定tls参数的值

确定您的集群是否已TLS启用是一个两步过程,您可以使用 AWS Management Console 或 AWS CLI执行此过程。

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

    Using the AWS Management Console
    1. 登录并打开亚马逊 DocumentDB 控制台,网址为 https://console.aws.amazon.com/docdb。 AWS Management Console

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

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

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

    Using the AWS CLI

    以下 AWS CLI 代码确定哪个参数控制您的集群。请确保将 sample-cluster 替换为您的集群的名称。

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

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

    [ [ "sample-cluster", "sample-parameter-group" ] ]
  2. 确定您的集群参数组中的 tls 参数的值。

    Using the AWS Management Console
    1. 在导航窗格中,选择参数组

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

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

    Using the AWS CLI

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

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

      • --db-cluster-parameter-group name – 必需。您的集群参数组的名称。

    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" } ] }
    注意

    亚马逊文档数据库支持 FIPS 140-3 个从亚马逊 DocumentDB 5.0(引擎版本 3.0.3727)开始的终端节点,位于以下区域:ca-central-1、us-west-2、us-east-1、us-east-1、us-east-2、us-east-2、-1、-1。 us-gov-east us-gov-west

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

在TLS启用状态下连接

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

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

wget https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem

如果你的应用程序在 Microsoft Windows 上并且需要一个PKCS7文件,你可以下载PKCS7证书包。此捆绑包包含中间证书和根证书,网址为 https://truststore.pki.rds.amazonaws.com/global/global- bundle.p7b。

Python

以下代码演示了在启用后如何使用 Python 连接到亚马逊文档数据库。TLS

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.us-east-1.docdb.amazonaws.com:27017/?tls=true&tlsCAFile=global-bundle.pem&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 连接到亚马逊文档数据库。

var MongoClient = require('mongodb').MongoClient //Create a MongoDB client, open a connection to DocDB; 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?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false', { tlsCAFile: `global-bundle.pem` //Specify the DocDB; cert }, 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

以下代码演示了如何在启用PHP时TLS使用连接到 Amazon DocumentDB。

<?php //Include Composer's autoloader require 'vendor/autoload.php'; $TLS_DIR = "/home/ubuntu/global-bundle.pem"; //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", ["tls" => "true", "tlsCAFile" => $TLS_DIR ]); //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

以下代码演示了在启用后如何使用 Go 连接到 Amazon DocumentDB。TLS

注意

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

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.us-east-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 集群时,您的程序必须使用 AWS提供的证书颁发机构 (CA) 文件来验证连接。要使用 Amazon RDS CA 证书,请执行以下操作:

  1. 从中下载 Amazon RDS CA 文件https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem

  2. 通过执行以下命令,使用该文件中包含的 CA 证书来创建信任存储。请务必更改 <truststorePassword> 换成别的东西。如果您要访问同时包含旧 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=<truststorePassword> curl -sS "https://truststore.pki.rds.amazonaws.com/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=<truststorePassword> curl -sS "https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem" > ${mydir}/global-bundle.pem split -p "-----BEGIN CERTIFICATE-----" ${mydir}/global-bundle.pem rds-ca- 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
  3. 请先在您的应用程序中设置以下系统属性,以便在该程序中使用 keystore,然后再连接到 Amazon DocumentDB 集群。

    javax.net.ssl.trustStore: <truststore> javax.net.ssl.trustStorePassword: <truststorePassword>
  4. 以下代码演示了启用TLS后如何使用 Java 连接到亚马逊文档数据库。

    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 = "<truststorePassword>"; 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# / .NET

以下代码演示了如何使用 C#/连接到亚马逊文档数据库。 NET何TLS时启用。

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}/sampledatabase?tls=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/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("sampledatabase"); var collection = database.GetCollection<BsonDocument>("samplecollection"); var docToInsert = new BsonDocument { { "pi", 3.14159 } }; collection.InsertOne(docToInsert); } } }
mongo shell

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

  1. 使用 mongo shell 连接到 Amazon DocumentDB。如果您使用的 mongo shell 版本早于 4.2,请使用以下代码进行连接。

    mongo --ssl --host sample-cluster.node.us-east-1.docdb.amazonaws.com:27017 --sslCAFile global-bundle.pem --username <sample-user> --password <password>

    如果您使用的版本等于或高于 4.2,请使用以下代码进行连接。文档AWS数据库不支持可重试写入。如果你使用的是旧版 mongo shell(不是 mongosh),请不要在任何代码字符串中包含该retryWrites=false命令。默认情况下,禁用可重试写入。包含retryWrites=false可能会导致正常读取命令失败。

    mongo --tls --host sample-cluster.node.us-east-1.docdb.amazonaws.com:27017 --tlsCAFile global-bundle.pem --username <sample-user> --password <password>
  2. 插入单个文档。

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

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

以下代码演示了启用后如何使用 mongolite (https://jeroen.github.io/mongolite/) 通过 R 连接到 Amazon Document TLS DB。

#Include the mongolite library. library(mongolite) mongourl <- paste("mongodb://<sample-user>:<password>@sample-cluster.node.us-east-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/global-bundle.pem>")) #Insert a single document str <- c('{"hello" : "Amazon DocumentDB"}') client$insert(str) #Find the document that was previously written client$find()
Ruby

以下代码演示了在启用 Ruby 后TLS如何使用 Ruby 连接到亚马逊文档数据库。

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/global-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 连接到亚马逊文档数据库。

## 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 连接到亚马逊文档数据库。

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

以下代码演示了如何在禁用PHP时TLS使用连接到 Amazon DocumentDB。

<?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。

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 连接到亚马逊文档数据库。

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# / .NET

以下代码演示了如何使用 C#/连接到亚马逊文档数据库。 NET何时TLS被禁用。

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); } } }
mongo shell

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

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

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

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

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

以下代码演示了在禁用时TLS如何使用 mongolite (https://jeroen.github.io/mongolite/) 通过 R 连接到 Amazon DocumentDB。

#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 连接到亚马逊文档数据库。

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>', 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