

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# プログラムによる Amazon DocumentDB への接続
<a name="connect_programmatically"></a>

このセクションでは、複数の言語を使用して Amazon DocumentDB (MongoDB 互換）に接続する方法を示すコード例を紹介します。コード例は、Transport Layer Security (TLS) が有効または無効になっているクラスターに接続しているかどうかに基づいて、2 つのセクションに分かれています。TLS は、新しい Amazon DocumentDB クラスターに対してデフォルトで有効になっています。ただし、必要に応じて TLS を無効にすることができます。詳細については、「[転送中のデータの暗号化](security.encryption.ssl.md)」を参照してください。

クラスターが存在する VPC の外部から Amazon DocumentDB に接続しようとしている場合は、「[Amazon VPC の外部から Amazon DocumentDB クラスターへの接続](connect-from-outside-a-vpc.md)」を参照してください。

クラスターに接続する前に、TLS がクラスターで有効になっているかどうかを把握しておく必要があります。次のセクションでは、`tls` または AWS マネジメントコンソール を使用してクラスターの AWS CLI パラメータの値を確認する方法について説明します。続いて、適切なコード例を見つけて適用する操作について説明します。

**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 マネジメントコンソール または AWS CLI を使用して実行できる 2 段階のプロセスで確認します。

1. **クラスターを管理しているパラメータグループを確認します。**

------
#### [ Using the AWS マネジメントコンソール ]

   1. AWS マネジメントコンソール にサインインして、Amazon DocumentDB コンソール [https://console.aws.amazon.com/docdb](https://console.aws.amazon.com/docdb) を開いてください。

   1. 左のナビゲーションペインで **[Clusters]** (クラスター) を選択します。

   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 マネジメントコンソール ]

   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は、Amazon DocumentDB 5.0 (エンジンバージョン 3.0.3727) クラスター以降、ca-central-1、us-west-2、us-east-1、us-east-2、us-gov-east-1、us-gov-west-1 リージョンで FIPS 140-3 エンドポイントをサポートします。

------

`tls` パラメータの値を確認したら、続いて以下のセクションのコード例のうち 1 つを使用してクラスターに接続します。
+ [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 が有効になっているときに Python を使用して Amazon DocumentDB に接続する方法を示しています。

**重要**  
なお、バージョン 6.13.1 より前の Node.js ドライバーには既知の制限事項があり、現在 Amazon DocumentDB の IAM ID 認証ではサポートされていません。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 が有効になっているときに Python を使用して Amazon DocumentDB に接続する方法を示しています。

次の例では、各 *ユーザー入力プレースホルダー* をクラスターの情報に置き換えます。

```
<?php
//Include Composer's autoloader
require 'vendor/autoload.php';

$TLS_DIR = "/home/ubuntu/global-bundle.pem";

//Create a MongoDB client and open connection to Amazon DocumentDB
$client = new MongoDB\Client("mongodb://sample-user:password@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/?retryWrites=false", ["tls" => "true", "tlsCAFile" => $TLS_DIR ]);

//Specify the database and collection to be used
$col = $client->sampledatabase->samplecollection;

//Insert a single document
$result = $col->insertOne( [ 'hello' => 'Amazon DocumentDB'] );

//Find the document that was previously written
$result = $col->findOne(array('hello' => 'Amazon DocumentDB'));

//Print the result to the screen
print_r($result);
?>
```

------
#### [ Go ]

次のコードは、TLS が有効になっているときに Go を使用して Amazon DocumentDB に接続する方法を示しています。

**注記**  
バージョン 1.2.1 現在、MongoDB Go ドライバーは `sslcertificateauthorityfile` にある最初の CA サーバー証明書のみを使用します。次のコード例では、この制限に対処するために、`sslcertificateauthorityfile` にあるすべてのサーバー証明書を、クライアントの作成時に使用されるカスタム TLS 設定に手動で追加しています。

次の例では*ユーザー入力プレースホルダー*をユーザー自身の情報で置き換えます。

```
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"

	"io/ioutil"
	"crypto/tls"
	"crypto/x509"
	"errors"
)

const (
	// Path to the AWS CA file
	caFilePath = "global-bundle.pem"

	// Timeout operations after N seconds
	connectTimeout  = 5
	queryTimeout    = 30
	username        = "sample-user"
	password        = "password"
	clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017"

	// Which instances to read from
	readPreference = "secondaryPreferred"

	connectionStringTemplate = "mongodb://%s:%s@%s/sample-database?tls=true&replicaSet=rs0&readpreference=%s"
)

func main() {

	connectionURI := fmt.Sprintf(connectionStringTemplate, username, password, clusterEndpoint, readPreference)

	tlsConfig, err := getCustomTLSConfig(caFilePath)
	if err != nil {
		log.Fatalf("Failed getting TLS configuration: %v", err)
	}

	client, err := mongo.NewClient(options.Client().ApplyURI(connectionURI).SetTLSConfig(tlsConfig))
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), connectTimeout*time.Second)
	defer cancel()

	err = client.Connect(ctx)
	if err != nil {
		log.Fatalf("Failed to connect to cluster: %v", err)
	}

	// Force a connection to verify our connection string
	err = client.Ping(ctx, nil)
	if err != nil {
		log.Fatalf("Failed to ping cluster: %v", err)
	}

	fmt.Println("Connected to DocumentDB!")

	collection := client.Database("sample-database").Collection("sample-collection")

	ctx, cancel = context.WithTimeout(context.Background(), queryTimeout*time.Second)
	defer cancel()

	res, err := collection.InsertOne(ctx, bson.M{"name": "pi", "value": 3.14159})
	if err != nil {
		log.Fatalf("Failed to insert document: %v", err)
	}

	id := res.InsertedID
	log.Printf("Inserted document ID: %s", id)

	ctx, cancel = context.WithTimeout(context.Background(), queryTimeout*time.Second)
	defer cancel()

	cur, err := collection.Find(ctx, bson.D{})

	if err != nil {
		log.Fatalf("Failed to run find query: %v", err)
	}
	defer cur.Close(ctx)

	for cur.Next(ctx) {
		var result bson.M
		err := cur.Decode(&result)
		log.Printf("Returned: %v", result)

		if err != nil {
			log.Fatal(err)
		}
	}

	if err := cur.Err(); err != nil {
		log.Fatal(err)
	}

}

func getCustomTLSConfig(caFile string) (*tls.Config, error) {
	tlsConfig := new(tls.Config)
	certs, err := ioutil.ReadFile(caFile)

	if err != nil {
		return tlsConfig, err
	}

	tlsConfig.RootCAs = x509.NewCertPool()
	ok := tlsConfig.RootCAs.AppendCertsFromPEM(certs)

	if !ok {
		return tlsConfig, errors.New("Failed parsing pem file")
	}

	return tlsConfig, nil
```

------
#### [ Java ]

Java アプリケーションから TLS が有効な Amazon DocumentDB クラスターに接続する場合、プログラムは AWS 提供の認証機関 (CA) ファイルを使用して接続を検証する必要があります。Amazon RDS CA 証明書を使用するには、以下の手順に従ってください。

1. Amazon RDS CA ファイルを [https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem](https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem) ダウンロード。

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 に接続**

**重要**  
なお、バージョン 6.13.1 より前の Node.js ドライバーには既知の制限事項があり、現在 Amazon DocumentDB の IAM ID 認証ではサポートされていません。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 かそれ以降のバージョンの Mongo シェルを使用している場合は、次のコードを使用して接続します。再試行可能な書き込みは Amazon DocumentDB ではサポートされていません。例外: mongo シェル を使用している場合は、どのコード文字列にも `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/)) を使用して Amazon DocumentDB に接続する方法を示しています。

次の例では、各 *ユーザー入力プレースホルダー* をクラスターの情報に置き換えます。

```
#Include the mongolite library.
library(mongolite)

mongourl <- paste("mongodb://sample-user:password@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/test2?ssl=true&",
          "readPreference=secondaryPreferred&replicaSet=rs0", sep="")
          
#Create a MongoDB client, open a connection to Amazon DocumentDB as a replica
#   set and specify the read preference as secondary preferred
client <-  mongo(url = mongourl, options = ssl_options(weak_cert_validation = F, ca ="<PATH/global-bundle.pem>"))

#Insert a single document
str <- c('{"hello" : "Amazon DocumentDB"}')
client$insert(str)

#Find the document that was previously written
client$find()
```

------
#### [ Ruby ]

次のコードは、TLS が有効になっているときに Ruby を使用して Amazon DocumentDB に接続する方法を示しています。

次の例では、各 *ユーザー入力プレースホルダー* をクラスターの情報に置き換えます。

```
require 'mongo'
require 'neatjson'
require 'json'
client_host = 'mongodb://sample-cluster.node.us-east-1.docdb.amazonaws.com:27017'
client_options = {
   database: 'test',
   replica_set: 'rs0',
   read: {:secondary_preferred => 1},
   user: 'sample-user',
   password: 'password',
   ssl: true,
   ssl_verify: true,
   ssl_ca_cert: 'PATH/global-bundle.pem',
   retry_writes: false
}


begin
   ##Create a MongoDB client, open a connection to Amazon DocumentDB as a
   ##   replica set and specify the read preference as secondary preferred
   client = Mongo::Client.new(client_host, client_options)
   
   ##Insert a single document
   x = client[:test].insert_one({"hello":"Amazon DocumentDB"})
   
   ##Find the document that was previously written
   result = client[:test].find()
   
   #Print the document
   result.each do |document|
      puts JSON.neat_generate(document)
   end
end

#Close the connection
client.close
```

------

## TLS が無効な場合の接続
<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 に接続する方法を示しています。

**重要**  
なお、バージョン 6.13.1 より前の Node.js ドライバーには既知の制限事項があり、現在 Amazon DocumentDB の IAM ID 認証ではサポートされていません。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 に接続**

**重要**  
なお、バージョン 6.13.1 より前の Node.js ドライバーには既知の制限事項があり、現在 Amazon DocumentDB の IAM ID 認証ではサポートされていません。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 かそれ以降のバージョンの Mongo シェルを使用している場合は、次のコードを使用して接続します。再試行可能な書き込みは Amazon DocumentDB ではサポートされていません。例外: mongo シェル を使用している場合は、どのコード文字列にも `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/)) を使用して 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
```

------