Amazon DocumentDB에 프로그래밍 방식으로 연결 - Amazon DocumentDB

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

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가 활성화되었는지 여부를 확인하는 작업은 또는 중 하나를 사용하여 수행할 수 있는 2단계 프로세스입니다. AWS Management Console AWS CLI

  1. 어느 파라미터 그룹이 클러스터를 관리하는지 결정합니다.

    Using the AWS Management Console
    1. 에 AWS Management Console로그인하고 https://console.aws.amazon.com/docdb 에서 Amazon DocumentDB 콘솔을 엽니다.

    2. 좌측 탐색 창에서 클러스터를 선택합니다.

    3. 클러스터 목록에서 클러스터 이름을 선택합니다.

    4. 결과 페이지에는 선택한 클러스터의 세부 정보가 표시됩니다. 클러스터 세부 정보까지 아래로 스크롤합니다. 해당 섹션의 하단에 있는 클러스터 파라미터 그룹 아래에서 파라미터 그룹의 이름을 찾습니다.

    Using the AWS CLI

    다음 AWS CLI 코드는 클러스터를 제어하는 파라미터를 결정합니다. sample-cluster를 클러스터의 이름으로 바꾸어야 합니다.

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

    이 작업의 출력은 다음과 같습니다.

    [ [ "sample-cluster", "sample-parameter-group" ] ]
  2. 클러스터의 파라미터 그룹에서 tls 파라미터의 값을 확인합니다.

    Using the AWS Management Console
    1. 탐색 창에서 파라미터 그룹을 선택합니다.

    2. 클러스터 파라미터 그룹 창에서 클러스터 파라미터 그룹을 선택합니다.

    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는 ca-central-1, us-west-2, us-east-1, us-east-2, us-east-2, us-east-2, -1, -1 등의 지역에서 아마존 DocumentDB 5.0 (엔진 버전 3.0.3727) 클러스터부터 FIPS 140-3 엔드포인트를 지원합니다. us-gov-east us-gov-west

tls 파라미터의 값을 확인했으면 이어서 다음 단원에 수록된 코드 예제 중 하나를 사용하여 클러스터에 연결합니다.

TLS가 활성화된 상태에서 연결

TLS 지원 Amazon DocumentDB 클러스터에 프로그램 방식으로 연결하는 코드 예제를 보려면 사용하려는 언어에 해당하는 탭을 선택합니다.

전송 중인 데이터를 암호화하려면 다음 작업을 사용하여 이름이 global-bundle.pem인 Amazon DocumentDB에 대한 퍼블릭 키를 다운로드합니다.

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

애플리케이션이 Microsoft Windows에서 실행되어 PKCS7 파일이 필요한 경우에는 PKCS7 인증서 번들을 다운로드할 수 있습니다. 이 번들에는 https://truststore.pki.rds.amazonaws.com/global/global-bundle.p7b의 중간 인증서와 루트 인증서가 모두 포함되어 있습니다.

Python

다음 코드는 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에 연결하는 방법을 보여줍니다.

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를 사용하여 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 클러스터에 연결하는 경우 프로그램은 제공된 인증 기관 (CA) 파일을 사용하여 AWS연결을 검증해야 합니다. Amazon RDS CA 인증서를 사용하려면 다음을 수행합니다.

  1. https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem 에서 Amazon RDS CA 파일을 다운로드하십시오.

  2. 다음 명령을 수행하여 파일에 포함된 CA 인증서로 트러스트 스토어를 생성합니다. <truststorePassword>를 다른 값으로 변경해야 합니다. 이전 CA 인증서(rds-ca-2015-root.pem)와 새 CA 인증서(rds-ca-2019-root.pem)가 모두 포함된 트러스트 저장소에 액세스하는 경우 인증서 번들을 트러스트 저장소로 가져올 수 있습니다.

    다음은 Linux 운영 체제에서 트러스트 스토어로 인증서 번들을 가져오는 샘플 셸 스크립트입니다. 다음은 자신의 정보를 각각의 사용자 입력 자리 표시자로 변경하는 예제입니다. 특히, 스크립트의 예제 디렉토리 "mydir “가 있으면 이 작업을 위해 생성한 디렉토리로 대체하십시오.

    mydir=/tmp/certs truststore=${mydir}/rds-truststore.jks storepassword=<truststorePassword> curl -sS "https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem" > ${mydir}/global-bundle.pem awk 'split_after == 1 {n++;split_after=0} /-----END CERTIFICATE-----/ {split_after=1}{print > "rds-ca-" n ".pem"}' < ${mydir}/global-bundle.pem for CERT in rds-ca-*; do alias=$(openssl x509 -noout -text -in $CERT | perl -ne 'next unless /Subject:/; s/.*(CN=|CN = )//; print') echo "Importing $alias" keytool -import -file ${CERT} -alias "${alias}" -storepass ${storepassword} -keystore ${truststore} -noprompt rm $CERT done rm ${mydir}/global-bundle.pem echo "Trust store content is: " keytool -list -v -keystore "$truststore" -storepass ${storepassword} | grep Alias | cut -d " " -f3- | while read alias do expiry=`keytool -list -v -keystore "$truststore" -storepass ${storepassword} -alias "${alias}" | grep Valid | perl -ne 'if(/until: (.*?)\n/) { print "$1\n"; }'` echo " Certificate ${alias} expires in '$expiry'" done

    다음은 macOS에서 트러스트 스토어로 인증서 번들을 가져오는 샘플 셸 스크립트입니다.

    mydir=/tmp/certs truststore=${mydir}/rds-truststore.jks storepassword=<truststorePassword> curl -sS "https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem" > ${mydir}/global-bundle.pem split -p "-----BEGIN CERTIFICATE-----" ${mydir}/global-bundle.pem rds-ca- for CERT in rds-ca-*; do alias=$(openssl x509 -noout -text -in $CERT | perl -ne 'next unless /Subject:/; s/.*(CN=|CN = )//; print') echo "Importing $alias" keytool -import -file ${CERT} -alias "${alias}" -storepass ${storepassword} -keystore ${truststore} -noprompt rm $CERT done rm ${mydir}/global-bundle.pem echo "Trust store content is: " keytool -list -v -keystore "$truststore" -storepass ${storepassword} | grep Alias | cut -d " " -f3- | while read alias do expiry=`keytool -list -v -keystore "$truststore" -storepass ${storepassword} -alias "${alias}" | grep Valid | perl -ne 'if(/until: (.*?)\n/) { print "$1\n"; }'` echo " Certificate ${alias} expires in '$expiry'" done
  3. Amazon DocumentDB 클러스터에 연결하기 전에 애플리케이션에서 다음 시스템 속성을 설정하여 프로그램에서 keystore를 사용합니다.

    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}/sampledatabase?tls=true&replicaSet=rs0&readpreference={3}"; string username = "<sample-user>"; string password = "<password>"; string readPreference = "secondaryPreferred"; string clusterEndpoint="sample-cluster.node.us-east-1.docdb.amazonaws.com:27017"; string connectionString = String.Format(template, username, password, clusterEndpoint, readPreference); string pathToCAFile = "<PATH/global-bundle.p7b_file>"; // ADD CA certificate to local trust store // DO this once - Maybe when your service starts X509Store localTrustStore = new X509Store(StoreName.Root); X509Certificate2Collection certificateCollection = new X509Certificate2Collection(); certificateCollection.Import(pathToCAFile); try { localTrustStore.Open(OpenFlags.ReadWrite); localTrustStore.AddRange(certificateCollection); } catch (Exception ex) { Console.WriteLine("Root certificate import failed: " + ex.Message); throw; } finally { localTrustStore.Close(); } var settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString)); var client = new MongoClient(settings); var database = client.GetDatabase("sampledatabase"); var collection = database.GetCollection<BsonDocument>("samplecollection"); var docToInsert = new BsonDocument { { "pi", 3.14159 } }; collection.InsertOne(docToInsert); } } }
mongo shell

다음 코드는 TLS가 활성화된 상태에서 mongo 셸을 사용하여 Amazon DocumentDB에 연결하고 쿼리하는 방법을 보여줍니다.

  1. 몽고 셸을 사용하여 Amazon DocumentDB에 연결합니다. 4.2 이전의 mongo 셸 버전을 사용하는 경우 다음 코드를 사용하여 연결하세요.

    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 셸을 사용하는 경우 코드 문자열에 retryWrites=false 명령을 포함시키지 마십시오. 기본적으로 재시도 가능한 쓰기는 비활성화되어 있습니다. retryWrites=false를 포함하면 일반 읽기 명령에서 오류가 발생할 수 있습니다.

    mongo --tls --host sample-cluster.node.us-east-1.docdb.amazonaws.com:27017 --tlsCAFile global-bundle.pem --username <sample-user> --password <password>
  2. 단일 문서를 삽입합니다.

    db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
  3. 이전에 삽입된 문서를 찾습니다.

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

다음 코드는 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에 연결하는 방법을 보여줍니다.

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 셸을 사용하여 Amazon DocumentDB에 연결하고 쿼리하는 방법을 보여줍니다.

  1. 몽고 셸을 사용하여 Amazon DocumentDB에 연결합니다.

    mongo --host mycluster.node.us-east-1.docdb.amazonaws.com:27017 --username <sample-user> --password <password>
  2. 단일 문서를 삽입합니다.

    db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
  3. 이전에 삽입된 문서를 찾습니다.

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

다음 코드는 TLS가 비활성화된 상태에서 mongolite(https://jeroen.github.io/mongolite/)를 사용하여 R을 Amazon DocumentDB에 연결하는 방법을 보여줍니다.

#Include the mongolite library. library(mongolite) #Create a MongoDB client, open a connection to Amazon DocumentDB as a replica # set and specify the read preference as secondary preferred client <- mongo(url = "mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/sample-database?readPreference=secondaryPreferred&replicaSet=rs0") ##Insert a single document str <- c('{"hello" : "Amazon DocumentDB"}') client$insert(str) ##Find the document that was previously written client$find()
Ruby

다음 코드는 TLS가 활성화된 상태에서 Ruby를 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