View a markdown version of this page

以程式設計方式連線至 Amazon DocumentDB - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

以程式設計方式連線至 Amazon DocumentDB

本節包含程式碼範例,示範如何使用數種不同的語言連線至 Amazon DocumentDB (具有 MongoDB 相容性)。範例會根據您連線的叢集已啟用或停用 Transport Layer Security (TLS),分成兩個部分。根據預設,在 Amazon DocumentDB 叢集上啟用 TLS。但如果您希望,您可以關閉 TLS。如需詳細資訊,請參閱加密傳輸中的資料

如果您嘗試從叢集所在的 VPC 外部連線至 Amazon DocumentDB,請參閱 從 Amazon VPC 外部連線至 Amazon DocumentDB 叢集

連線到您的叢集之前,您必須知道叢集是否已啟用 TLS。下節示範如何使用 AWS 管理主控台 或 AWS CLI判斷叢集的 tls 參數值。然後,您就可以尋找和套用適當的程式碼範例,繼續作業。

判斷tls參數的值

判斷叢集是否已啟用 TLS,是您可以使用 AWS 管理主控台 或 執行的兩個步驟程序 AWS CLI。

  1. 判斷管理您叢集的參數群組。

    Using the AWS 管理主控台
    1. 登入 AWS 管理主控台,並在 https://https://console.aws.amazon.com/docdb 開啟 Amazon DocumentDB 主控台。

    2. 在左側導覽窗格中選擇叢集

    3. 在叢集清單中,選取您叢集的名稱。

    4. 產生的頁面會顯示您所選取叢集的詳細資訊。選取 Configuration (組態) 索引標籤。在組態和狀態區段中,找到叢集參數群組下方的參數群組名稱。

    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 管理主控台
    1. 在導覽窗格中,選擇 Parameter groups (參數群組)。

    2. 叢集參數群組視窗中,從步驟 1d 選取叢集參數群組名稱。

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

    Amazon DocumentDB 支援從這些區域中 Amazon DocumentDB 5.0 (引擎版本 3.0.3727) 叢集開始的 FIPS 140-3 端點:ca-central-1、us-west-2、us-east-1、us-east-2、us-gov-east-1、us-gov-west-1。

判斷 tls 參數值之後,請使用後續章節的其中一個程式碼範例來繼續連線您的叢集。

使用已啟用的 TLS 連線

若要以程式設計方式檢視連線至啟用 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

下列程式碼示範如何在啟用 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=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 連線至 Amazon DocumentDB。

重要

6.13.1 版之前的 Node.js 驅動程式有已知的限制,Amazon DocumentDB 的 IAM 身分驗證目前不支援此限制。使用 Node.js 驅動程式的 Node.js 驅動程式和工具 (例如 mongosh) 必須升級為使用 Node.js 驅動程式 6.13.1 版或更新版本。

在下列範例中,將每個使用者輸入預留位置取代為您叢集的資訊。

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

下列程式碼示範如何在啟用 TLS 時使用 PHP 連線至 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

下列程式碼示範如何在啟用 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 = "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. 從 下載 https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem Amazon RDS CA 檔案。

  2. 執行以下命令,建立將憑證授權機構憑證包含在檔案的信任存放區。請務必將 truststore-password 變更為其他項目。如果您正在存取同時包含舊憑證授權機構憑證 (rds-ca-2015-root.pem) 和新憑證授權機構憑證 (rds-ca-2019-root.pem) 的信任存放區,您可以將憑證套件匯入信任存放區。

    以下範例 Shell 指令碼將憑證套件匯入 Linux 作業系統上的信任存放區。在下列範例中,將每個使用者輸入預留位置取代為您自己的資訊。最值得注意的是,只要範例目錄「mydir」位於指令碼中,將其取代為您為此任務建立的目錄。

    mydir=/tmp/certs truststore=${mydir}/rds-truststore.jks storepassword=truststore-password 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=truststore-password 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. 在連線到 Amazon DocumentDB 叢集之前,請在應用程式中設定下列系統屬性,以在keystore程式中使用 。

    javax.net.ssl.trustStore: truststore javax.net.ssl.trustStorePassword: truststore-password;
  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 = "truststore-password"; System.setProperty("javax.net.ssl.trustStore", truststore); System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword); MongoClient mongoClient = MongoClients.create(connectionString); MongoDatabase testDB = mongoClient.getDatabase("sample-database"); MongoCollection<Document> numbersCollection = testDB.getCollection("sample-collection"); Document doc = new Document("name", "pi").append("value", 3.14159); numbersCollection.insertOne(doc); MongoCursor<Document> cursor = numbersCollection.find().iterator(); try { while (cursor.hasNext()) { System.out.println(cursor.next().toJson()); } } finally { cursor.close(); } } }
C# / .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}/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); } } }
MongoDB Shell

下列程式碼示範如何在啟用 TLS 時,使用最新版本、mongosh 或先前的 mongo shell 版本來連線至和查詢 Amazon DocumentDB。

使用 mongosh 連線至 Amazon DocumentDB

重要

6.13.1 版之前的 Node.js 驅動程式有已知的限制,Amazon DocumentDB 的 IAM 身分驗證目前不支援此限制。使用 Node.js 驅動程式的 Node.js 驅動程式和工具 (例如 mongosh) 必須升級為使用 Node.js 驅動程式 6.13.1 版或更新版本。

在下列範例中,將每個使用者輸入預留位置取代為您叢集的資訊。

mongosh --tls --host cluster-end-point:27017 --tlsCAFile global-bundle.pem --username sample-user --password password --retryWrites false

使用先前的 mongo shell 版本連線至 Amazon DocumentDB

如果您使用 IAM,則必須使用舊版的 mongo shell。輸入下列其中一個命令選項:

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

如果您使用的版本等於或大於 4.2,請使用下列程式碼進行連線。Amazon DocumentDB 不支援可重試寫入。如果您使用的是舊版 mongo shell (非 mongosh),請勿在任何程式碼字串中包含 retryWrites=false命令。預設會停用可重試寫入。包含 retryWrites=false 可能會導致正常讀取命令失敗。

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

測試連線

  1. 插入單一文件。

    db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
  2. 尋找之前插入的文件。

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

下列程式碼示範如何在啟用 TLS 時使用 mongolite (https://jeroen.github.io/mongolite/) 以 R 連線至 Amazon DocumentDB。

在下列範例中,將每個使用者輸入預留位置取代為您叢集的資訊。

#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 連線至 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/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 連線至 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。

重要

6.13.1 版之前的 Node.js 驅動程式有已知的限制,Amazon DocumentDB 的 IAM 身分驗證目前不支援此限制。使用 Node.js 驅動程式的 Node.js 驅動程式和工具 (例如 mongosh) 必須升級為使用 Node.js 驅動程式 6.13.1 版或更新版本。

在下列範例中,將每個使用者輸入預留位置取代為您叢集的資訊。

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); } } }
MongoDB Shell

下列程式碼示範如何在停用 TLS 時,使用最新版本、mongosh 或先前的 mongo shell 版本來連線至和查詢 Amazon DocumentDB。

使用 mongosh 連線至 Amazon DocumentDB

重要

6.13.1 版之前的 Node.js 驅動程式有已知的限制,Amazon DocumentDB 的 IAM 身分驗證目前不支援此限制。使用 Node.js 驅動程式的 Node.js 驅動程式和工具 (例如 mongosh) 必須升級為使用 Node.js 驅動程式 6.13.1 版或更新版本。

在下列範例中,將每個使用者輸入預留位置取代為您叢集的資訊。

mongosh --host cluster-end-point:27017 --username sample-user --password password --retryWrites false

使用先前的 mongo shell 版本連線至 Amazon DocumentDB

如果您使用 IAM,則必須使用舊版的 mongo shell。輸入下列其中一個命令選項:

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

如果您使用的版本等於或大於 4.2,請使用下列程式碼進行連線。Amazon DocumentDB 不支援可重試寫入。如果您使用的是舊版 mongo shell (非 mongosh),請勿在任何程式碼字串中包含 retryWrites=false命令。預設會停用可重試寫入。包含 retryWrites=false 可能會導致正常讀取命令失敗。

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

測試連線

  1. 插入單一文件。

    db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
  2. 尋找之前插入的文件。

    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 連線至 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', 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