기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
Amazon DocumentDB에 프로그래밍 방식으로 연결
이 섹션에는 다양한 언어를 사용하여 Amazon DocumentDB(MongoDB 호환)에 연결하는 방법을 보여주는 코드 예제가 포함되어 있습니다. 이들 예제는 전송 계층 보안(TLS)이 활성화 또는 비활성화된 클러스터에 연결하는지에 따라 두 가지로 구분됩니다. 기본적으로 Amazon DocumentDB 클러스터에서는 TLS가 활성화됩니다. 하지만 원할 경우 TLS를 비활성화할 수 있습니다. 자세한 내용은 전송 중 데이터 암호화 단원을 참조하십시오.
클러스터가 있는 VPC 외부에서 Amazon DocumentDB에 연결하려는 경우 섹션을 참조하세요Amazon VPC 외부에서 Amazon DocumentDB 클러스터에 연결.
클러스터에 연결하기 전에 클러스터에서 TLS가 활성화되어 있는지 여부를 알아야 합니다. 다음 섹션에서는 AWS Management Console 또는 AWS CLI를 사용하여 클러스터의 tls 파라미터 값을 확인하는 방법을 설명합니다. 그런 다음 적절한 코드 예제를 찾아 적용할 수 있습니다.
tls 파라미터 값 확인
클러스터에 TLS가 활성화되어 있는지 여부를 결정하는 것은 AWS Management Console 또는를 사용하여 수행할 수 있는 2단계 프로세스입니다 AWS CLI.
-
어느 파라미터 그룹이 클러스터를 관리하는지 결정합니다.
- Using the AWS Management Console
-
-
에 로그인 AWS Management Console하고 https://console.aws.amazon.com/docdb
Amazon DocumentDB 콘솔을 엽니다. -
좌측 탐색 창에서 클러스터를 선택합니다.
-
클러스터 목록에서 클러스터 이름을 선택합니다.
-
결과 페이지에는 선택한 클러스터의 세부 정보가 표시됩니다. [구성(Configuration)] 탭을 선택합니다. 구성 및 상태 섹션의 클러스터 파라미터 그룹 아래에서 파라미터 그룹의 이름을 찾습니다.
-
- Using the AWS CLI
-
다음 AWS CLI 코드는 클러스터를 관리하는 파라미터를 결정합니다.
를 클러스터의 이름으로 바꿔야 합니다.sample-clusteraws docdb describe-db-clusters \ --db-cluster-identifiersample-cluster\ --query 'DBClusters[*].[DBClusterIdentifier,DBClusterParameterGroup]'이 작업의 출력은 다음과 같이 표시됩니다.
[ [ "sample-cluster", "sample-parameter-group" ] ]
-
클러스터의 파라미터 그룹에서
tls파라미터의 값을 확인합니다.- Using the AWS Management Console
-
-
탐색 창에서 파라미터 그룹을 선택합니다.
-
클러스터 파라미터 그룹 창에서 1단계의 클러스터 파라미터 그룹 이름을 선택합니다.
-
결과 페이지에는 클러스터 파라미터 그룹의 파라미터가 표시됩니다. 여기서
tls파라미터의 값을 볼 수 있습니다. 이 파라미터 수정에 대한 자세한 내용은 Amazon DocumentDB 클러스터 파라미터 그룹 수정 섹션을 참조하세요.
-
- Using the AWS CLI
-
describe-db-cluster-parametersAWS CLI 명령을 사용하여 클러스터 파라미터 그룹의 파라미터 세부 정보를 볼 수 있습니다.-
--describe-db-cluster-parameters- 파라미터 그룹 내의 모든 파라미터와 해당 값을 나열합니다.-
--db-cluster-parameter-group name- 필수입니다. 클러스터 파라미터 그룹의 이름입니다.
-
다음 예제에서는 각각의
사용자 입력 자리 표시자를 자신의 클러스터 정보로 바꿉니다.aws docdb describe-db-cluster-parameters \ --db-cluster-parameter-group-namesample-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는 ca-central-1, us-west-2, us-east-1, us-east-2, us-gov-east-1, us-gov-west-1 리전에서 Amazon DocumentDB 5.0(엔진 버전 3.0.3727) 클러스터로 시작하는 FIPS 140-3 엔드포인트를 지원합니다.
-
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에 연결하는 방법을 보여줍니다.
중요
Amazon DocumentDB에 대한 IAM ID 인증에서 지원되지 않는 Node.js 드라이버(6.13.1 이전 버전)에는 알려진 제한 사항이 있습니다. 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 Driver는
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 인증서를 사용하려면 다음을 수행합니다.
-
https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem
에서 Amazon RDS CA 파일을 다운로드하세요. -
다음 명령을 수행하여 파일에 포함된 CA 인증서로 트러스트 스토어를 생성합니다.
truststore-password를 다른 값으로 변경해야 합니다. 이전 CA 인증서(rds-ca-2015-root.pem)와 새 CA 인증서(rds-ca-2019-root.pem)가 모두 포함된 트러스트 저장소에 액세스하는 경우 인증서 번들을 트러스트 저장소로 가져올 수 있습니다.다음은 Linux 운영 체제에서 트러스트 스토어로 인증서 번들을 가져오는 샘플 쉘 스크립트입니다. 다음 예에서는 자신의 정보로 각각의
사용자 입력 자리 표시자를 바꿉니다. 특히 예제 디렉터리 "mydir"가 스크립트에 있는 경우 이 작업을 위해 생성한 디렉터리로 교체합니다.mydir=/tmp/certs truststore=${mydir}/rds-truststore.jks storepassword=truststore-passwordcurl -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다음은 macOS에서 트러스트 스토어로 인증서 번들을 가져오는 샘플 쉘 스크립트입니다.
mydir=/tmp/certs truststore=${mydir}/rds-truststore.jks storepassword=truststore-passwordcurl -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 -
Amazon DocumentDB 클러스터에 연결하기 전에 애플리케이션에서 다음 시스템 속성을 설정하여 프로그램에서
keystore를 사용합니다.javax.net.ssl.trustStore:truststorejavax.net.ssl.trustStorePassword:truststore-password; -
다음 코드는 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 쉘 버전을 사용하여 Amazon DocumentDB에 연결하고 쿼리하는 방법을 보여줍니다.
mongosh를 사용하여 Amazon DocumentDB에 연결
중요
Amazon DocumentDB에 대한 IAM ID 인증에서 지원되지 않는 Node.js 드라이버(6.13.1 이전 버전)에는 알려진 제한 사항이 있습니다. Node.js 드라이버를 사용하는 Node.js 드라이버 및 도구(예: mongosh)는 Node.js 드라이버 버전 6.13.1 이상을 사용하도록 업그레이드해야 합니다.
다음 예제에서는 각각의
사용자 입력 자리 표시자를 자신의 클러스터 정보로 바꿉니다.mongosh --tls --hostcluster-end-point:27017 --tlsCAFile global-bundle.pem --usernamesample-user--passwordpassword--retryWrites false이전의 Mongo 쉘 버전을 사용하여 Amazon DocumentDB에 연결
IAM을 사용하는 경우 이전 버전의 Mongo 쉘을 사용해야 합니다. 다음 명령 옵션 중 하나를 입력합니다.
mongo --ssl --hostcluster-end-point:27017 --sslCAFile global-bundle.pem --usernamesample-user--passwordpassword4.2 이상의 버전을 사용하는 경우 다음 코드를 사용하여 연결하세요. Amazon DocumentDB에서는 재시도 가능한 쓰기가 지원되지 않습니다. mongo 쉘(mongosh 제외)을 사용하는 경우 코드 문자열에
retryWrites=false명령을 포함시키지 마십시오. 기본적으로 재시도 가능한 쓰기는 비활성화되어 있습니다.retryWrites=false를 포함하면 일반 읽기 명령에서 오류가 발생할 수 있습니다.mongo --tls --hostcluster-end-point:27017 --tlsCAFile global-bundle.pem --usernamesample-user--passwordpassword연결 테스트
단일 문서를 삽입합니다.
db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})이전에 삽입된 문서를 찾습니다.
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가 활성화된 상태에서 Java를 사용하여 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에 연결하는 방법을 보여줍니다.
중요
Amazon DocumentDB에 대한 IAM ID 인증에서 지원되지 않는 Node.js 드라이버(6.13.1 이전 버전)에는 알려진 제한 사항이 있습니다. 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 쉘 버전을 사용하여 Amazon DocumentDB에 연결하고 쿼리하는 방법을 보여줍니다.
mongosh를 사용하여 Amazon DocumentDB에 연결
중요
Amazon DocumentDB에 대한 IAM ID 인증에서 지원되지 않는 Node.js 드라이버(6.13.1 이전 버전)에는 알려진 제한 사항이 있습니다. Node.js 드라이버를 사용하는 Node.js 드라이버 및 도구(예: mongosh)는 Node.js 드라이버 버전 6.13.1 이상을 사용하도록 업그레이드해야 합니다.
다음 예제에서는 각각의
사용자 입력 자리 표시자를 자신의 클러스터 정보로 바꿉니다.mongosh --hostcluster-end-point:27017 --usernamesample-user--passwordpassword--retryWrites false이전의 Mongo 쉘 버전을 사용하여 Amazon DocumentDB에 연결
IAM을 사용하는 경우 이전 버전의 Mongo 쉘을 사용해야 합니다. 다음 명령 옵션 중 하나를 입력합니다.
mongo --hostcluster-end-point:27017 --usernamesample-user--passwordpassword4.2 이상의 버전을 사용하는 경우 다음 코드를 사용하여 연결하세요. Amazon DocumentDB에서는 재시도 가능한 쓰기가 지원되지 않습니다. mongo 쉘(mongosh 제외)을 사용하는 경우 코드 문자열에
retryWrites=false명령을 포함시키지 마십시오. 기본적으로 재시도 가능한 쓰기는 비활성화되어 있습니다.retryWrites=false를 포함하면 일반 읽기 명령에서 오류가 발생할 수 있습니다.mongo --hostcluster-end-point:27017 --usernamesample-user--passwordpassword연결 테스트
단일 문서를 삽입합니다.
db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})이전에 삽입된 문서를 찾습니다.
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
Amazon DocumentDB의 네트워크 압축
유선 프로토콜 압축을 사용하면 애플리케이션이 네트워크를 통해 전송하는 데이터를 줄일 수 있습니다. Amazon DocumentDB 8.0.1 이상은 압축을 지원합니다. 대용량 문서 또는 대용량 결과 세트를 전송하는 워크로드의 처리량이 향상됩니다. 압축을 활성화하면 드라이버와 서버가 압축된 메시지를 교환합니다.
네트워크 압축을 활성화하면 CPU 리소스를 거래하여 네트워크 대역폭을 줄일 수 있습니다. 워크로드가 네트워크 바운드이고 대용량 페이로드를 전송할 때 압축을 활성화합니다. 작은 요청 및 응답의 경우 압축 오버헤드가 절감액을 초과할 수 있으므로 순 이점이 보이지 않을 수 있습니다.
지원되는 압축기
Amazon DocumentDB는 snappy 압축기를 지원합니다. Amazon DocumentDB는 zlib 및와 같이 MongoDB 드라이버가 제공하는 다른 압축기를 지원하지 않습니다zstd.
드라이버가 압축기 목록을 요청하는 경우 Amazon DocumentDB는 지원되는 압축기만 협상합니다. 예를 들어 드라이버가 snappy 및를 제공하는 경우 zstd Amazon DocumentDB는를 선택하고 snappy 무시합니다zstd. 드라이버가 지원되지 않는 압축기만 제공하는 경우 Amazon DocumentDB는 연결을 압축하지 않습니다. 이 경우 드라이버와 서버는 압축 없이 메시지를 교환합니다.
압축 활성화
압축을 활성화하려면 연결 문자열에 compressors 옵션을 추가하고 로 설정합니다snappy. 다음 연결 문자열에서 , 및 passwordusername를 고유한 값으로 바꿉니다.docdb-cluster-endpoint
mongodb://username:password@docdb-cluster-endpoint:27017/?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false&compressors=snappy
MongoDB 드라이버를 사용하는 경우 드라이버의 연결 옵션을 통해 동일한 옵션을 설정합니다. 대부분의 드라이버는 스냅 압축을 수행하기 위해 추가 클라이언트 측 종속성이 필요합니다.
-
Node.js 드라이버에는
snappy패키지가 필요합니다. -
Python 드라이버(
PyMongo)에는python-snappy패키지가 필요합니다. Linux에서는 시스템 스냅 라이브러리python-snappy도 필요합니다(예:dnf또는를snappy-devel통해yum).
정확한 옵션 이름과 필요한 패키지는 드라이버 설명서를 참조하세요.
참고
클라이언트 측 압축 종속성이 누락된 경우 드라이버가 성공적으로 연결됩니다. 그러나 압축 없이 메시지를 교환하고 오류를 반환하지 않습니다. 압축이 활성 상태인지 확인하려면에 설명된 대로 협상된 압축기를 확인합니다압축 확인.
다음 Python 코드 예제는 스냅 압축이 활성화된 클러스터에 연결하고 try 및 except 블록을 사용하여 연결 오류를 처리합니다.
import pymongo try: client = pymongo.MongoClient( 'mongodb://username:password@docdb-cluster-endpoint:27017/' '?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false' '&compressors=snappy', tlsCAFile='global-bundle.pem') db = client['sample-database'] col = db['sample-collection'] col.insert_one({'item': 'DocumentDB'}) print(col.find_one()) except Exception as error: print(f'Connection failed: {error}')
압축 확인
드라이버와 Amazon DocumentDB가 압축을 협상했는지 확인하려면 hello MongoDB 유선 프로토콜 명령이 반환하는 compression 필드를 검사합니다. 드라이버와 Amazon DocumentDB가 압축을 협상할 때이 필드에는 합의된 압축기가 나열됩니다.