

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Menghubungkan secara terprogram ke Amazon DocumentDB
<a name="connect_programmatically"></a>

Bagian ini berisi contoh kode yang menunjukkan cara menghubungkan ke Amazon DocumentDB (dengan kompatibilitas MongoDB) menggunakan beberapa bahasa yang berbeda. Contoh dipisahkan menjadi dua bagian berdasarkan apakah Anda terhubung ke klaster yang memiliki Keamanan Lapisan Pengangkutan (TLS) diaktifkan atau dinonaktifkan. Secara default, TLS diaktifkan di klaster Amazon DocumentDB. Namun, Anda dapat menonaktifkan TLS jika Anda mau. Untuk informasi selengkapnya, lihat [Mengenkripsi data dalam perjalanan](security.encryption.ssl.md). 

Jika Anda mencoba untuk terhubung ke Amazon DocumentDB Anda dari luar VPC di mana klaster Anda berada, silakan lihat [Menghubungkan ke cluster Amazon DocumentDB dari luar Amazon VPC](connect-from-outside-a-vpc.md). 

Sebelum Anda terhubung ke klaster Anda, Anda harus tahu apakah TLS diaktifkan di klaster. Bagian berikutnya menunjukkan kepada Anda bagaimana untuk menentukan nilai parameter `tls` klaster Anda menggunakan Konsol Manajemen AWS atau AWS CLI. Setelah itu, Anda dapat melanjutkan dengan menemukan dan menerapkan contoh kode yang sesuai.

**Topics**
+ [

## Menentukan nilai `tls` parameter Anda
](#connect_programmatically-determine_tls_value)
+ [

## Menghubungkan dengan TLS diaktifkan
](#connect_programmatically-tls_enabled)
+ [

## Menghubungkan dengan TLS dinonaktifkan
](#connect_programmatically-tls_disabled)

## Menentukan nilai `tls` parameter Anda
<a name="connect_programmatically-determine_tls_value"></a>

Menentukan apakah klaster Anda mengaktifkan TLS adalah proses dua langkah yang dapat Anda lakukan menggunakan atau. Konsol Manajemen AWS AWS CLI

1. **Tentukan grup parameter mana yang mengatur cluster Anda.**

------
#### [ Using the Konsol Manajemen AWS ]

   1. [Masuk ke Konsol Manajemen AWS, dan buka konsol Amazon DocumentDB di /docdb. https://console.aws.amazon.com](https://console.aws.amazon.com/docdb)

   1. Pada panel navigasi sebelah kiri, pilih **Klaster**.

   1. Dalam daftar klaster, pilih nama klaster Anda.

   1. Halaman yang dihasilkan menunjukkan detail klaster yang Anda pilih. Pilih tab **Konfigurasi**. Di bagian **Konfigurasi dan status**, cari nama grup parameter di bawah **grup parameter Cluster**.

------
#### [ Using the AWS CLI ]

    AWS CLI Kode berikut menentukan parameter mana yang mengatur cluster Anda. Pastikan Anda mengganti *`sample-cluster`* dengan nama klaster Anda.

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

   Keluaran dari operasi ini terlihat seperti berikut ini:

   ```
   [
          [
              "sample-cluster",
              "sample-parameter-group"
          ]
   ]
   ```

------

1. **Tentukan nilai `tls` parameter dalam grup parameter cluster Anda.**

------
#### [ Using the Konsol Manajemen AWS ]

   1. Di panel navigasi, pilih **Grup parameter**.

   1. Di jendela **grup parameter Cluster**, pilih nama grup parameter cluster Anda dari Langkah 1d.

   1. Halaman yang dihasilkan menunjukkan parameter grup parameter klaster Anda. Anda dapat melihat nilai dari parameter `tls` di sini. Untuk informasi tentang memodifikasi parameter ini, lihat [Memodifikasi grup parameter cluster Amazon DocumentDB](cluster_parameter_groups-modify.md).

------
#### [ Using the AWS CLI ]

   Anda dapat menggunakan `describe-db-cluster-parameters` AWS CLI perintah untuk melihat detail parameter dalam grup parameter cluster Anda.
   + **`--describe-db-cluster-parameters`** — Untuk membuat daftar semua parameter di dalam grup parameter dan nilainya.
     + **`--db-cluster-parameter-group name`** — Diperlukan. Nama grup parameter klaster Anda.

   Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

   ```
   aws docdb describe-db-cluster-parameters \
       --db-cluster-parameter-group-name sample-parameter-group
   ```

   Keluaran dari operasi ini terlihat seperti berikut ini: 

   ```
   {
           "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"
               }
           ]
   }
   ```

**catatan**  
Amazon DocumentDB mendukung FIPS 140-3 endpoint dimulai dengan Amazon DocumentDB 5.0 (versi engine 3.0.3727) cluster di wilayah ini: ca-central-1, us-west-2, us-east-1, us-east-1, us-east-2, us-east-2, -1. us-gov-east us-gov-west

------

Setelah menentukan nilai dari parameter `tls` Anda, lanjutkan menghubungkan ke klaster Anda dengan menggunakan salah satu contoh kode di bagian berikut.
+ [Menghubungkan dengan TLS diaktifkan](#connect_programmatically-tls_enabled) 
+ [Menghubungkan dengan TLS dinonaktifkan](#connect_programmatically-tls_disabled) 

## Menghubungkan dengan TLS diaktifkan
<a name="connect_programmatically-tls_enabled"></a>

Untuk melihat contoh kode guna menghubungkan secara terprogram ke klaster Amazon DocumentDB dengan TLS yang diaktifkan, pilih tab yang sesuai untuk bahasa yang ingin Anda gunakan.

Untuk mengenkripsi data dalam perjalanan, unduh kunci publik untuk Amazon `global-bundle.pem` DocumentDB bernama menggunakan operasi berikut.

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

Jika aplikasi Anda ada di Microsoft Windows dan memerlukan PKCS7 file, Anda dapat mengunduh bundel PKCS7 sertifikat. Bundel ini berisi sertifikat perantara dan root di [https://truststore.pki.rds.amazonaws.com/global/global-bundle.p7b](https://truststore.pki.rds.amazonaws.com/global/global-bundle.p7b).

------
#### [ Python ]

Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB menggunakan Python ketika TLS diaktifkan.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

```
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 ]

Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB menggunakan Node.js ketika TLS diaktifkan.

**penting**  
Ada batasan yang diketahui dengan driver Node.js yang lebih lama dari versi 6.13.1, yang saat ini tidak didukung oleh otentikasi identitas IAM untuk Amazon DocumentDB. Driver dan alat Node.js yang menggunakan driver Node.js (misalnya, mongosh) harus ditingkatkan untuk menggunakan driver Node.js versi 6.13.1 atau lebih tinggi.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

```
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 ]

Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB menggunakan PHP ketika TLS diaktifkan.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

```
<?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 ]

Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB menggunakan Go ketika TLS diaktifkan.

**catatan**  
Pada versi 1.2.1, Driver MongoDB Go hanya akan menggunakan sertifikat server CA pertama yang ditemukan di `sslcertificateauthorityfile`. Contoh kode di bawah ini mengatasi batasan ini dengan menambahkan semua sertifikat server secara manual yang ditemukan di `sslcertificateauthorityfile` ke konfigurasi TLS kustom yang digunakan selama pembuatan klien. 

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

```
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 ]

Saat menyambungkan ke klaster Amazon DocumentDB yang mendukung TLS dari aplikasi Java, program Anda harus menggunakan file otoritas sertifikat (CA) AWS yang disediakan untuk memvalidasi koneksi. Untuk menggunakan sertifikat CA Amazon RDS, lakukan hal berikut:

1. Unduh file CA Amazon RDS dari [https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem](https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem) .

1. Buat penyimpanan kepercayaan dengan sertifikat CA yang terdapat dalam file dengan melakukan perintah berikut. Pastikan untuk mengubah *truststore-password* ke sesuatu yang lain. Jika Anda mengakses penyimpanan kepercayaan yang berisi sertifikat CA lama (`rds-ca-2015-root.pem`) dan sertifikat CA baru (`rds-ca-2019-root.pem`), Anda dapat mengimpor paket sertifikat ke dalam penyimpanan kepercayaan. 

   Berikut adalah contoh skrip shell yang mengimpor paket sertifikat ke trust store di sistem operasi Linux. Dalam contoh berikut, ganti masing-masing *user input placeholder * dengan informasi Anda sendiri. Terutama, di mana pun direktori contoh "*mydir*" berada di skrip, gantilah dengan direktori yang Anda buat untuk tugas ini.

   ```
   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
   ```

   Berikut adalah contoh skrip shell yang mengimpor paket sertifikat ke trust store di sistem operasi 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. Gunakan `keystore` di program Anda dengan mengatur properti sistem berikut di aplikasi Anda sebelum membuat koneksi ke klaster Amazon DocumentDB.

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

1. Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB menggunakan Java ketika TLS diaktifkan.

   Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

   ```
   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 ]

Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB menggunakan C\$1 / .NET ketika TLS diaktifkan.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

```
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 ]

Kode berikut menunjukkan cara menghubungkan ke dan kueri Amazon DocumentDB menggunakan versi terbaru, mongosh, atau versi shell mongo sebelumnya, saat TLS diaktifkan.

**Connect ke Amazon DocumentDB dengan mongosh**

**penting**  
Ada batasan yang diketahui dengan driver Node.js yang lebih lama dari versi 6.13.1, yang saat ini tidak didukung oleh otentikasi identitas IAM untuk Amazon DocumentDB. Driver dan alat Node.js yang menggunakan driver Node.js (misalnya, mongosh) harus ditingkatkan untuk menggunakan driver Node.js versi 6.13.1 atau lebih tinggi.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

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

**Connect ke Amazon DocumentDB dengan versi shell mongo sebelumnya**

Jika Anda menggunakan IAM, Anda harus menggunakan versi mongo shell sebelumnya. Masukkan salah satu opsi perintah berikut:

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

Jika Anda menggunakan versi yang sama dengan atau lebih besar dari 4.2, gunakan kode berikut untuk menghubungkan. Tulisan yang dapat dicoba ulang tidak didukung di Amazon DocumentDB. Jika Anda menggunakan shell mongo lama (bukan mongosh), jangan sertakan `retryWrites=false` perintah dalam string kode apa pun. Secara default, penulisan yang dapat dicoba ulang dinonaktifkan. Termasuk `retryWrites=false` dapat menyebabkan kegagalan dalam perintah baca normal.

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

**Uji koneksi**

1. Masukkan dokumen tunggal.

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

1. Temukan dokumen yang sebelumnya dimasukkan.

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

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

Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB dengan R menggunakan mongolite ([https://jeroen.github.io/mongolite/](https://jeroen.github.io/mongolite/)) ketika TLS diaktifkan.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

```
#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 ]

Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB dengan Ruby ketika TLS diaktifkan.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

```
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
```

------

## Menghubungkan dengan TLS dinonaktifkan
<a name="connect_programmatically-tls_disabled"></a>

Untuk melihat contoh kode guna menghubungkan secara terprogram ke klaster Amazon DocumentDB dengan TLS yang dinonaktifkan, pilih tab untuk bahasa yang ingin Anda gunakan.

------
#### [ Python ]

Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB menggunakan Python ketika TLS dinonaktifkan.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

```
## 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 ]

Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB menggunakan Node.js ketika TLS dinonaktifkan.

**penting**  
Ada batasan yang diketahui dengan driver Node.js yang lebih lama dari versi 6.13.1, yang saat ini tidak didukung oleh otentikasi identitas IAM untuk Amazon DocumentDB. Driver dan alat Node.js yang menggunakan driver Node.js (misalnya, mongosh) harus ditingkatkan untuk menggunakan driver Node.js versi 6.13.1 atau lebih tinggi.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

```
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 ]

Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB menggunakan PHP ketika TLS dinonaktifkan.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

```
<?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 ]

Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB menggunakan Go ketika TLS dinonaktifkan.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

```
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 ]

Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB menggunakan Java ketika TLS dinonaktifkan.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

```
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 ]

Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB menggunakan C\$1 / .NET ketika TLS dinonaktifkan.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

```
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 ]

Kode berikut menunjukkan cara menghubungkan ke dan kueri Amazon DocumentDB menggunakan versi terbaru, mongosh, atau versi shell mongo sebelumnya, ketika TLS dinonaktifkan.

**Connect ke Amazon DocumentDB dengan mongosh**

**penting**  
Ada batasan yang diketahui dengan driver Node.js yang lebih lama dari versi 6.13.1, yang saat ini tidak didukung oleh otentikasi identitas IAM untuk Amazon DocumentDB. Driver dan alat Node.js yang menggunakan driver Node.js (misalnya, mongosh) harus ditingkatkan untuk menggunakan driver Node.js versi 6.13.1 atau lebih tinggi.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

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

**Connect ke Amazon DocumentDB dengan versi shell mongo sebelumnya**

Jika Anda menggunakan IAM, Anda harus menggunakan versi mongo shell sebelumnya. Masukkan salah satu opsi perintah berikut:

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

Jika Anda menggunakan versi yang sama dengan atau lebih besar dari 4.2, gunakan kode berikut untuk menghubungkan. Tulisan yang dapat dicoba ulang tidak didukung di Amazon DocumentDB. Jika Anda menggunakan shell mongo lama (bukan mongosh), jangan sertakan `retryWrites=false` perintah dalam string kode apa pun. Secara default, penulisan yang dapat dicoba ulang dinonaktifkan. Termasuk `retryWrites=false` dapat menyebabkan kegagalan dalam perintah baca normal.

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

**Uji koneksi**

1. Masukkan dokumen tunggal.

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

1. Temukan dokumen yang sebelumnya dimasukkan.

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

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

Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB dengan R menggunakan mongolite ([https://jeroen.github.io/mongolite/](https://jeroen.github.io/mongolite/)) ketika TLS dinonaktifkan.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

```
#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 ]

Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB dengan Ruby ketika TLS dinonaktifkan.

Dalam contoh berikut, ganti masing-masing *user input placeholder* dengan informasi cluster Anda.

```
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
```

------