本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
以编程方式连接到亚马逊 DocumentDB
本节包含的代码示例演示如何使用几种不同的语言连接至亚马逊 DocumentDB(兼容 MongoDB)。根据连接的集群是否启用传输层安全性 (TLS),这些示例分为两个部分。默认情况下,亚马逊 DocumentDB 集群上启用 TLS。但是,您可以根据需要关闭 TLS。有关更多信息,请参阅加密传输中的数据:
如果您想要从集群所在的 VPC 之外连接到 Amazon DocumentDB,请参阅从亚马逊 VPC 外部连接到亚马逊 DocumentDB 集群。
在连接到集群之前,您必须知道集群是否启用了 TLS。下一部分介绍如何使用 AWS Management Console或 AWS CLI 确定集群的 tls
参数的值。之后,您可以查找和应用适当的代码示例。
确定 tls
参数的值
确定集群是否启用了 TLS 是一个两步过程,您可以使用 AWS Management Console或 AWS CLI 执行该过程。
-
确定管理集群的参数组。
- Using the AWS Management Console
-
-
登录AWS Management Console,然后打开亚马逊 DocumentDB 控制台,网址为https://console.aws.amazon.com/docdb
。 -
在左侧导航窗格中,选择集群。
-
在集群列表中,选择您的集群的名称。
-
生成的页面将显示所选集群的详细信息。向下滚动到 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" ] ]
-
确定您的集群参数组中的
tls
参数的值。- Using the AWS Management Console
-
-
在导航窗格中,选择参数组。
-
在集群参数组窗口中,选择您的集群参数组。
-
打开的页面上会显示您的集群参数组中包含的参数。您可以在其中查看
tls
参数的值。有关修改此参数的信息,请参阅修改亚马逊 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" } ] }
-
确定 tls
参数的值后,即可使用以下部分中的代码示例之一继续连接到您的集群。
启用了 TLS 的情况下的连接
要查看以编程方式连接到支持 TLS 的 Amazon DocumentDB 集群的代码示例,请为要使用的语言选择相应的选项卡。
要加密传输中的数据,请下载名为 Amazon DocumentDB 的公钥global-bundle.pem
使用以下操作。
wget https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem
如果您的应用程序在 Microsoft Windows 上并且需要 PKCS7 文件,则可以下载 PKCS7 证书捆绑包。此捆绑包包含中间证书和根证书,网址为https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem。
- Python
-
以下代码演示了在启用 TLS 时如何使用 Python 连接到亚马逊 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=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 连接到亚马逊 DocumentDB。
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':'DocDB;'}, function(err, result){ //Print the result to the screen console.log(result); //Close the connection client.close() }); }); }); - PHP
-
以下代码演示了在启用 TLS 时如何使用 PHP 连接到亚马逊 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
-
以下代码演示了在启用 TLS 时如何使用 Go 连接到亚马逊 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 = "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 证书,请执行以下操作:
-
从以下网址下载亚马逊 RDS CA 文件https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem
。 -
通过执行以下命令,使用该文件中包含的 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://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://s3.amazonaws.com/rds-downloads/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 -
使用
keystore
在与 Amazon DocumentDB 集群建立连接之前,在应用程序中设置以下系统属性。javax.net.ssl.trustStore:
<truststore>
javax.net.ssl.trustStorePassword:<truststorePassword>
-
以下代码演示了在启用 TLS 时如何使用 Java 连接到亚马逊 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 连接到亚马逊 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}/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.pem_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
-
以下代码演示了在启用 TLS 时如何使用 mongo shell 连接和查询 Amazon DocumentDB。
-
使用 mongo 外壳连接到亚马逊 DocumentDB。如果您使用的是低于 4.2 的 mongo shell 版本,请使用以下代码进行连接。
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 DocumentDB 不支持可重试写入。例外:如果你使用的是 mongo shell,请不要包含
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>
-
插入单个文档。
db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
-
查找以前插入的文档。
db.myTestCollection.find({'hello':'Amazon DocumentDB'})
-
- R
-
以下代码演示了如何使用蒙古语通过 R 连接到亚马逊 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/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
-
以下代码演示了在启用 TLS 时如何使用 Ruby 连接到亚马逊 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/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 连接到亚马逊 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 连接到亚马逊 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 连接到亚马逊 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 连接到亚马逊 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 连接到亚马逊 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 连接到亚马逊 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。
-
使用 mongo 外壳连接到亚马逊 DocumentDB。
mongo --host
mycluster.node.us-east-1
.docdb.amazonaws.com:27017 --username<sample-user>
--password<password>
-
插入单个文档。
db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
-
查找以前插入的文档。
db.myTestCollection.find({'hello':'Amazon DocumentDB'})
-
- R
-
以下代码演示了如何使用蒙古语通过 R 连接到亚马逊 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 连接到亚马逊 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>
', 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