

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

# Amazon DocumentDB에 프로그래밍 방식으로 연결
<a name="connect_programmatically"></a>

이 섹션에는 다양한 언어를 사용하여 Amazon DocumentDB(MongoDB 호환)에 연결하는 방법을 보여주는 코드 예제가 포함되어 있습니다. 이들 예제는 전송 계층 보안(TLS)이 활성화 또는 비활성화된 클러스터에 연결하는지에 따라 두 가지로 구분됩니다. 기본적으로 Amazon DocumentDB 클러스터에서는 TLS가 활성화됩니다. 하지만 원할 경우 TLS를 비활성화할 수 있습니다. 자세한 내용은 [전송 중 데이터 암호화](security.encryption.ssl.md) 단원을 참조하십시오.

클러스터가 상주하는 VPC 외부에서 Amazon DocumentDB에 연결하려는 경우 [Amazon VPC 외부에서 Amazon DocumentDB 클러스터에 연결](connect-from-outside-a-vpc.md) 섹션을 참조하세요.

클러스터에 연결하기 전에 클러스터에서 TLS가 활성화되어 있는지 여부를 알아야 합니다. 다음 섹션에서는 AWS Management Console 또는 AWS CLI를 사용하여 클러스터의 `tls` 파라미터 값을 확인하는 방법을 설명합니다. 그런 다음 적절한 코드 예제를 찾아 적용할 수 있습니다.

**Topics**
+ [`tls` 파라미터 값 확인](#connect_programmatically-determine_tls_value)
+ [TLS가 활성화된 상태에서 연결](#connect_programmatically-tls_enabled)
+ [TLS가 비활성화된 상태에서 연결](#connect_programmatically-tls_disabled)

## `tls` 파라미터 값 확인
<a name="connect_programmatically-determine_tls_value"></a>

클러스터에 TLS 활성화가 되었는지 확인하는 절차는 AWS Management Console 또는 AWS CLI를 사용하여 두 단계로 수행할 수 있습니다.

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

------
#### [ Using the AWS Management Console ]

   1. AWS Management Console에 로그인한 후 [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb)에서 Amazon DocumentDB 콘솔을 엽니다.

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

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

   1. 결과 페이지에는 선택한 클러스터의 세부 정보가 표시됩니다. [**구성(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"
          ]
   ]
   ```

------

1. **클러스터의 파라미터 그룹에서 `tls` 파라미터의 값을 확인합니다.**

------
#### [ Using the AWS Management Console ]

   1. 탐색 창에서 **파라미터 그룹**을 선택합니다.

   1. **클러스터 파라미터 그룹** 창에서 1단계의 클러스터 파라미터 그룹 이름을 선택합니다.

   1. 결과 페이지에는 클러스터 파라미터 그룹의 파라미터가 표시됩니다. 여기서 `tls` 파라미터의 값을 볼 수 있습니다. 이 파라미터 수정에 대한 자세한 내용은 [Amazon DocumentDB 클러스터 파라미터 그룹 수정](cluster_parameter_groups-modify.md) 섹션을 참조하세요.

------
#### [ 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-gov-east-1, us-gov-west-1 리전에서 Amazon DocumentDB 5.0 (엔진 버전 3.0.3727) 클러스터부터 FIPS 140-3 엔드포인트를 지원합니다.

------

`tls` 파라미터의 값을 확인했으면 이어서 다음 섹션에 수록된 코드 예제 중 하나를 사용하여 클러스터에 연결합니다.
+ [TLS가 활성화된 상태에서 연결](#connect_programmatically-tls_enabled) 
+ [TLS가 비활성화된 상태에서 연결](#connect_programmatically-tls_disabled) 

## TLS가 활성화된 상태에서 연결
<a name="connect_programmatically-tls_enabled"></a>

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](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 인증서를 사용하려면 다음을 수행합니다.

1. [https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem](https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem) 에서 Amazon RDS CA 파일을 다운로드하세요.

1. 다음 명령을 수행하여 파일에 포함된 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-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
   ```

   다음은 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
   ```

1. Amazon DocumentDB 클러스터에 연결하기 전에 애플리케이션에서 다음 시스템 속성을 설정하여 프로그램에서 `keystore`를 사용합니다.

   ```
   javax.net.ssl.trustStore: truststore
   javax.net.ssl.trustStorePassword: truststore-password;
   ```

1. 다음 코드는 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\$1 / .NET ]

다음 코드는 TLS가 활성화된 상태에서 C\$1 / .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 --host cluster-end-point:27017 --tlsCAFile  global-bundle.pem --username sample-user --password password --retryWrites false
```

**이전의 Mongo 쉘 버전을 사용하여 Amazon DocumentDB에 연결**

IAM을 사용하는 경우 이전 버전의 Mongo 쉘을 사용해야 합니다. 다음 명령 옵션 중 하나를 입력합니다.

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

4.2 이상의 버전을 사용하는 경우 다음 코드를 사용하여 연결하세요. Amazon DocumentDB에서는 재시도 가능한 쓰기가 지원되지 않습니다. mongo 쉘(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'})
   ```

1. 이전에 삽입된 문서를 찾습니다.

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

------
#### [ R ]

다음 코드는 TLS가 활성화된 상태에서 mongolite([https://jeroen.github.io/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가 비활성화된 상태에서 연결
<a name="connect_programmatically-tls_disabled"></a>

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\$1 / .NET ]

다음 코드는 TLS가 비활성화된 상태에서 C\$1 / .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 --host cluster-end-point:27017 --username sample-user --password password --retryWrites false
```

**이전의 Mongo 쉘 버전을 사용하여 Amazon DocumentDB에 연결**

IAM을 사용하는 경우 이전 버전의 Mongo 쉘을 사용해야 합니다. 다음 명령 옵션 중 하나를 입력합니다.

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

4.2 이상의 버전을 사용하는 경우 다음 코드를 사용하여 연결하세요. Amazon DocumentDB에서는 재시도 가능한 쓰기가 지원되지 않습니다. mongo 쉘(mongosh 제외)을 사용하는 경우 코드 문자열에 `retryWrites=false` 명령을 포함시키지 마십시오. 기본적으로 재시도 가능한 쓰기는 비활성화되어 있습니다. `retryWrites=false`를 포함하면 일반 읽기 명령에서 오류가 발생할 수 있습니다.

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

**연결을 테스트합니다**

1. 단일 문서를 삽입합니다.

   ```
   db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
   ```

1. 이전에 삽입된 문서를 찾습니다.

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

------
#### [ R ]

다음 코드는 TLS가 비활성화된 상태에서 mongolite([https://jeroen.github.io/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
```

------