以编程方式连接到 Amazon DocumentDB - Amazon DocumentDB
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

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

以编程方式连接到 Amazon DocumentDB

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

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

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

确定 tls 参数的值

确定集群是否启用了 TLS 是一个两步过程,您可以使用 Amazon Web Services Management Console或 Amazon CLI 执行该过程。

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

    1. 登录到Amazon Web Services Management Console,然后在以下位置打开 Amazon DocumentDB 控制台https://console.aws.amazon.com/docdb.

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

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

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

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

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

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

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

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

    2. 集群参数组窗口中,选择您的集群参数组。

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

    您可以使用 describe-db-cluster-parameters Amazon 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", "IsModifiable": true, "ApplyMethod": "pending-reboot" } ] }

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

启用了 TLS 的情况下的连接

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

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

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

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

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=rds-combined-ca-cn-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。

var MongoClient = require('mongodb').MongoClient, f = require('util').format, fs = require('fs'); //Specify the Amazon DocumentDB cert var ca = [fs.readFileSync("rds-combined-ca-cn-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.us-east-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。

<?php //Include Composer's autoloader require 'vendor/autoload.php'; $SSL_DIR = "/home/ubuntu"; $SSL_FILE = "rds-combined-ca-cn-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.us-east-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 配置来解决此限制。

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

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

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

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

    mydir=/tmp/certs truststore=${mydir}/rds-truststore.jks storepassword=<truststorePassword> curl -sS "https://s3.cn-north-1.amazonaws.com.cn/rds-downloads/rds-combined-ca-cn-bundle.pem" > ${mydir}/rds-combined-ca-cn-bundle.pem awk 'split_after == 1 {n++;split_after=0} /-----END CERTIFICATE-----/ {split_after=1}{print > "rds-ca-" n ".pem"}' < ${mydir}/rds-combined-ca--cn-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}/rds-combined-ca--cn-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://s3.cn-north-1.amazonaws.com.cn/rds-downloads/rds-combined-ca-cn-bundle.pem" > ${mydir}/rds-combined-ca-bundle.pem split -p "-----BEGIN CERTIFICATE-----" ${mydir}/rds-combined-ca-cn-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}/rds-combined-ca-cn-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 连接到 Amazon DocumentDB。

    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

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

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_rds-combined-ca-cn-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); } } }
mongo shell

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

  1. 使用 mongo shell Connect 到 Amazon DocumentDB。如果你使用的是 4.2 之前的 mongo shell 版本,请使用以下代码进行连接。

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

    如果你使用的是等于或大于 4.2 的 mongo shell 版本,请使用以下代码进行连接。

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

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

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

以下代码说明了如何使用蒙古人使用 R 连接到 Amazon DocumentDB。https://jeroen.github.io/mongolite/) 启用了 TLS 的情况下。

#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/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。

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

禁用了 TLS 的情况下的连接

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

Python

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

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

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。

<?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 连接到 Amazon DocumentDB。

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

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

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 Connect 到 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

以下代码说明了如何使用蒙古人使用 R 连接到 Amazon DocumentDB。https://jeroen.github.io/mongolite/) 当 TLS 被禁用时。

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

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