Connecting Programmatically to Amazon DocumentDB

This section contains code examples that demonstrate how to connect to Amazon DocumentDB (with MongoDB compatibility) using several different languages. The examples are separated into two sections based on whether you are connecting to a cluster that has Transport Layer Security (TLS) enabled or disabled. By default, TLS is enabled on Amazon DocumentDB clusters. However, you can turn off TLS if you want. For more information, see Encrypting Data in Transit.

If you are attempting to connect to your Amazon DocumentDB from outside the VPC in which your cluster resides, please see Connecting to an Amazon DocumentDB Cluster from Outside an Amazon VPC.

Before you connect to your cluster, you must know whether TLS is enabled on the cluster. The next section shows you how to determine the value of your cluster’s tls parameter using either the AWS Management Console or the AWS CLI. Following that, you can continue by finding and applying the appropriate code example.

Determining the Value of Your tls Parameter

Determining whether your cluster has TLS enabled is a two-step process that you can perform using either the AWS Management Console or AWS CLI.

  1. Determine which parameter group is governing your cluster.

  2. Sign in to the AWS Management Console, and open the Amazon DocumentDB console at https://console.aws.amazon.com/docdb.

  3. In the left navigation pane, choose Clusters.
  4. In the list of clusters, select the name of your cluster.
  5. The resulting page shows the details of the cluster that you selected. Scroll down to Cluster details. At the bottom of that section, locate the parameter group’s name below Cluster parameter group.

The following AWS CLI code determines which parameter is governing your cluster. Make sure you replace sample-cluster with the name of your cluster.

```

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

Output from this operation looks something like the following:

```

  1. [
  2. [
  3. "sample-cluster",
  4. "sample-parameter-group"
  5. ]
  6. ] ```
  7. Determine the value of the tls parameter in your cluster’s parameter group.

  8. In the navigation pane, choose Parameter groups.

  9. In the Cluster parameter groups window, select your cluster parameter group.
  10. The resulting page shows your cluster parameter group’s parameters. You can see the value of the tls parameter here. For information on modifying this parameter, see Modifying Amazon DocumentDB Cluster Parameter Groups.

You can use the describe-db-cluster-parameters AWS CLI command to view the details of the parameters in your cluster parameter group.

  • --describe-db-cluster-parameters — To list all the parameters inside a parameter group and their values.

    • --db-cluster-parameter-group name — Required. The name of your cluster parameter group.

1. ```
2. aws docdb describe-db-cluster-parameters \
3. --db-cluster-parameter-group-name sample-parameter-group
4. ```

6. Output from this operation looks something like the following:

8. ```
9. {
10. "Parameters": [
11. {
12. "ParameterName": "profiler_threshold_ms",
13. "ParameterValue": "100",
14. "Description": "Operations longer than profiler_threshold_ms will be logged",
15. "Source": "system",
16. "ApplyType": "dynamic",
17. "DataType": "integer",
18. "AllowedValues": "50-2147483646",
19. "IsModifiable": true,
20. "ApplyMethod": "pending-reboot"
21. },
22. {
23. "ParameterName": "tls",
24. "ParameterValue": "disabled",
25. "Description": "Config to enable/disable TLS",
26. "Source": "user",
27. "ApplyType": "static",
28. "DataType": "string",
29. "AllowedValues": "disabled,enabled",
30. "IsModifiable": true,
31. "ApplyMethod": "pending-reboot"
32. }
33. ]
34. }
35. ```

After determining the value of your tls parameter, continue connecting to your cluster by using one of the code examples in the following sections.

Connecting with TLS Enabled

To view a code example for programmatically connecting to a TLS-enabled Amazon DocumentDB cluster, choose the appropriate tab for the language that you want to use.

To encrypt data in transit, download the public key for Amazon DocumentDB named rds-combined-ca-bundle.pem using the following operation.


1. wget https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem

Python

The following code demonstrates how to connect to Amazon DocumentDB using Python when TLS is enabled.


1. import pymongo
2. import sys

4. ##Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set and specify the read preference as secondary preferred
5. client = pymongo.MongoClient('mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/?ssl=true&ssl_ca_certs=rds-combined-ca-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred')

7. ##Specify the database to be used
8. db = client.sample_database

10. ##Specify the collection to be used
11. col = db.sample_collection

13. ##Insert a single document
14. col.insert_one({'hello':'Amazon DocumentDB'})

16. ##Find the document that was previously written
17. x = col.find_one({'hello':'Amazon DocumentDB'})

19. ##Print the result to the screen
20. print(x)

22. ##Close the connection
23. client.close()

Node.js

The following code demonstrates how to connect to Amazon DocumentDB using Node.js when TLS is enabled.


1. var MongoClient = require('mongodb').MongoClient,
2. f = require('util').format,
3. fs = require('fs');

5. //Specify the Amazon DocumentDB cert
6. var ca = [fs.readFileSync("rds-combined-ca-bundle.pem")];

8. //Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set,
9. //  and specify the read preference as secondary preferred
10. var client = MongoClient.connect(
11. 'mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/sample-database?ssl=true&replicaSet=rs0&readPreference=secondaryPreferred',
12. {
13. sslValidate: true,
14. sslCA:ca,
15. useNewUrlParser: true
16. },
17. function(err, client) {
18. if(err)
19. throw err;

21. //Specify the database to be used
22. db = client.db('sample-database');

24. //Specify the collection to be used
25. col = db.collection('sample-collection');

27. //Insert a single document
28. col.insertOne({'hello':'Amazon DocumentDB'}, function(err, result){
29. //Find the document that was previously written
30. col.findOne({'hello':'Amazon DocumentDB'}, function(err, result){
31. //Print the result to the screen
32. console.log(result);

34. //Close the connection
35. client.close()
36. });
37. });
38. });

PHP

The following code demonstrates how to connect to Amazon DocumentDB using PHP when TLS is enabled.


1. <?php
2. //Include Composer's autoloader
3. require 'vendor/autoload.php';

5. $SSL_DIR = "/home/ubuntu";
6. $SSL_FILE = "rds-combined-ca-bundle.pem";

8. //Specify the Amazon DocumentDB cert
9. $ctx = stream_context_create(array(
10. "ssl" => array(
11. "cafile" => $SSL_DIR . "/" . $SSL_FILE,
12. ))
13. );

15. //Create a MongoDB client and open connection to Amazon DocumentDB
16. $client = new MongoDB\Client("mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017", array("ssl" => true), array("context" => $ctx));

18. //Specify the database and collection to be used
19. $col = $client->sample-database->sample-collection;

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

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

27. //Print the result to the screen
28. print_r($result);
29. ?>

Go

The following code demonstrates how to connect to Amazon DocumentDB using Go when TLS is enabled.

Note

As of version 1.2.1, the MongoDB Go Driver will only use the first CA server certificate found in sslcertificateauthorityfile. The example code below addresses this limitation by manually appending all server certificates found in sslcertificateauthorityfile to a custom TLS configuration used during client creation.


1. package main

3. import (
4. "context"
5. "fmt"
6. "log"
7. "time"

9. "go.mongodb.org/mongo-driver/bson"
10. "go.mongodb.org/mongo-driver/mongo"
11. "go.mongodb.org/mongo-driver/mongo/options"

13. "io/ioutil"
14. "crypto/tls"
15. "crypto/x509"
16. "errors"
17. )

19. const (
20. // Path to the AWS CA file
21. caFilePath = "rds-combined-ca-bundle.pem"

23. // Timeout operations after N seconds
24. connectTimeout  = 5
25. queryTimeout    = 30
26. username        = "<sample-user>"
27. password        = "<password>"
28. clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017"

30. // Which instances to read from
31. readPreference = "secondaryPreferred"

33. connectionStringTemplate = "mongodb://%s:%s@%s/sample-database?ssl=true&replicaSet=rs0&readpreference=%s"
34. )

36. func main() {

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

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

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

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

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

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

64. fmt.Println("Connected to DocumentDB!")

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

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

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

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

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

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

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

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

94. if err != nil {
95. log.Fatal(err)
96. }
97. }

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

103. }

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

109. if err != nil {
110. return tlsConfig, err
111. }

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

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

120. return tlsConfig, nil
121. }

Java

When connecting to a TLS-enabled Amazon DocumentDB cluster from a Java application, your program must use the AWS-provided certificate authority (CA) file to validate the connection. To use the Amazon RDS CA certificate, do the following:

  1. Download the Amazon RDS CA file from https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem .
  2. Create a trust store with the CA certificate contained in the file by performing the following commands. Be sure to change the <truststorePassword> to something else. If you are accessing a trust store that contains both the old CA certificate (rds-ca-2015-root.pem) and the new CA certificate (rds-ca-2019-root.pem), you can import the certificate bundle into the trust store.

The following is a sample shell script that imports the certificate bundle into a trust store on a Linux operating system.

```

  1. mydir=/tmp/certs
  2. truststore=${mydir}/rds-truststore.jks
  3. storepassword=

  4. curl -sS "https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem" > ${mydir}/rds-combined-ca-bundle.pem

  5. awk 'split_after == 1 {n++;split_after=0} /-----END CERTIFICATE-----/ {split_after=1}{print > "rds-ca-" n ".pem"}' < ${mydir}/rds-combined-ca-bundle.pem

  6. for CERT in rds-ca-*; do

  7. alias=$(openssl x509 -noout -text -in $CERT | perl -ne 'next unless /Subject:/; s/.*(CN=|CN = )//; print')
  8. echo "Importing $alias"
  9. keytool -import -file ${CERT} -alias "${alias}" -storepass ${storepassword} -keystore ${truststore} -noprompt
  10. rm $CERT
  11. done

  12. rm ${mydir}/rds-combined-ca-bundle.pem

  13. echo "Trust store content is: "

  14. keytool -list -v -keystore "$truststore" -storepass ${storepassword} | grep Alias | cut -d " " -f3- | while read alias

  15. do
  16. expiry=keytool -list -v -keystore "$truststore" -storepass ${storepassword} -alias "${alias}" | grep Valid | perl -ne 'if(/until: (.*?)\n/) { print "$1\n"; }'
  17. echo " Certificate ${alias} expires in '$expiry'"
  18. done ```

The following is a sample shell script that imports the certificate bundle into a trust store on macOS.

```

  1. mydir=/tmp/certs
  2. truststore=${mydir}/rds-truststore.jks
  3. storepassword=

  4. curl -sS "https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem" > ${mydir}/rds-combined-ca-bundle.pem

  5. split -p "-----BEGIN CERTIFICATE-----" ${mydir}/rds-combined-ca-bundle.pem rds-ca-

  6. for CERT in rds-ca-*; do

  7. alias=$(openssl x509 -noout -text -in $CERT | perl -ne 'next unless /Subject:/; s/.*(CN=|CN = )//; print')
  8. echo "Importing $alias"
  9. keytool -import -file ${CERT} -alias "${alias}" -storepass ${storepassword} -keystore ${truststore} -noprompt
  10. rm $CERT
  11. done

  12. rm ${mydir}/rds-combined-ca-bundle.pem

  13. echo "Trust store content is: "

  14. keytool -list -v -keystore "$truststore" -storepass ${storepassword} | grep Alias | cut -d " " -f3- | while read alias

  15. do
  16. expiry=keytool -list -v -keystore "$truststore" -storepass ${storepassword} -alias "${alias}" | grep Valid | perl -ne 'if(/until: (.*?)\n/) { print "$1\n"; }'
  17. echo " Certificate ${alias} expires in '$expiry'"
  18. done ```
  19. Use the keystore in your program by setting the following system properties in your application before making a connection to the Amazon DocumentDB cluster.

```

  1. javax.net.ssl.trustStore:
  2. javax.net.ssl.trustStorePassword: ```
  3. The following code demonstrates how to connect to Amazon DocumentDB using Java when TLS is enabled.

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


1. public final class Main {
2. private Main() {
3. }
4. public static void main(String[] args) {

6. String template = "mongodb://%s:%s@%s/sample-database?ssl=true&replicaSet=rs0&readpreference=%s";
7. String username = "<sample-user>";
8. String password = "<password>";
9. String clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
10. String readPreference = "secondaryPreferred";
11. String connectionString = String.format(template, username, password, clusterEndpoint, readPreference);

13. String truststore = "<truststore>";
14. String truststorePassword = "<truststorePassword>";

16. System.setProperty("javax.net.ssl.trustStore", truststore);
17. System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);

19. MongoClientURI clientURI = new MongoClientURI(connectionString);
20. MongoClient mongoClient = new MongoClient(clientURI);

22. MongoDatabase testDB = mongoClient.getDatabase("sample-database");
23. MongoCollection<Document> numbersCollection = testDB.getCollection("sample-collection");

25. Document doc = new Document("name", "pi").append("value", 3.14159);
26. numbersCollection.insertOne(doc);

28. MongoCursor<Document> cursor = numbersCollection.find().iterator();
29. try {
30. while (cursor.hasNext()) {
31. System.out.println(cursor.next().toJson());
32. }
33. } finally {
34. cursor.close();
35. }

37. }
38. }

40. ```

C# / .NET

The following code demonstrates how to connect to Amazon DocumentDB using C# / .NET when TLS is enabled.


1. using System;
2. using System.Text;
3. using System.Linq;
4. using System.Collections.Generic;
5. using System.Security.Cryptography;
6. using System.Security.Cryptography.X509Certificates;
7. using System.Net.Security;
8. using MongoDB.Driver;
9. using MongoDB.Bson;

11. namespace DocDB
12. {
13. class Program
14. {
15. static void Main(string[] args)
16. {
17. string template = "mongodb://{0}:{1}@{2}/sample-database?ssl=true&replicaSet=rs0&readpreference={3}";
18. string username = "<sample-user>";
19. string password = "<password>";
20. string readPreference = "secondaryPreferred";
21. string clusterEndpoint="sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
22. string connectionString = String.Format(template, username, password, clusterEndpoint, readPreference);

24. string pathToCAFile = "<path_to_rds-combined-ca-bundle.p7b_file>";

26. // ADD CA certificate to local trust store
27. // DO this once - Maybe when your service starts
28. X509Store localTrustStore = new X509Store(StoreName.Root);
29. X509Certificate2Collection certificateCollection = new X509Certificate2Collection();
30. certificateCollection.Import(pathToCAFile);
31. try
32. {
33. localTrustStore.Open(OpenFlags.ReadWrite);
34. localTrustStore.AddRange(certificateCollection);
35. }
36. catch (Exception ex)
37. {
38. Console.WriteLine("Root certificate import failed: " + ex.Message);
39. throw;
40. }
41. finally
42. {
43. localTrustStore.Close();
44. }

46. var settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
47. var client = new MongoClient(settings);

49. var database = client.GetDatabase("sample-database");
50. var collection = database.GetCollection<BsonDocument>("sample-collection");
51. var docToInsert = new BsonDocument { { "pi", 3.14159 } };
52. collection.InsertOne(docToInsert);
53. }
54. }
55. }

mongo shell

The following code demonstrates how to connect to and query Amazon DocumentDB using the mongo shell when TLS is enabled.

  1. Connect to Amazon DocumentDB with the mongo shell.

```

  1. mongo --ssl --host sample-cluster.node.us-east-1.docdb.amazonaws.com:27017 --sslCAFile rds-combined-ca-bundle.pem --username --password ```
  2. Insert a single document.

```

  1. db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'}) ```
  2. Find the document that was previously inserted.

```

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

R

The following code demonstrates how to connect to Amazon DocumentDB with R using mongolite (https://jeroen.github.io/mongolite/) when TLS is enabled.


1. #Include the mongolite library.
2. library(mongolite)

4. mongourl <- paste("mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/test2?ssl=true&",
5. "readPreference=secondaryPreferred&replicaSet=rs0", sep="")

7. #Create a MongoDB client, open a connection to Amazon DocumentDB as a replica
8. #   set and specify the read preference as secondary preferred
9. client <- mongo(url = mongo(url = mongourl, options = ssl_options(weak_cert_validation = F, ca = <path to 'rds-combined-ca-bundle.pem'>))

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

15. #Find the document that was previously written
16. client$find()

Ruby

The following code demonstrates how to connect to Amazon DocumentDB with Ruby when TLS is enabled.


1. require 'mongo'
2. require 'neatjson'
3. require 'json'
4. client_host = 'mongodb://sample-cluster.node.us-east-1.docdb.amazonaws.com:27017'
5. client_options = {
6. database: 'test',
7. replica_set: 'rs0',
8. read: {:secondary_preferred => 1},
9. user: '<sample-user>',
10. password: '<password>',
11. ssl: true,
12. ssl_verify: true,
13. ssl_ca_cert: <path to 'rds-combined-ca-bundle.pem'>
14. }

16. begin
17. ##Create a MongoDB client, open a connection to Amazon DocumentDB as a
18. ##   replica set and specify the read preference as secondary preferred
19. client = Mongo::Client.new(client_host, client_options)

21. ##Insert a single document
22. x = client[:test].insert_one({"hello":"Amazon DocumentDB"})

24. ##Find the document that was previously written
25. result = client[:test].find()

27. #Print the document
28. result.each do |document|
29. puts JSON.neat_generate(document)
30. end
31. end

33. #Close the connection
34. client.close

Connecting with TLS Disabled

To view a code example for programmatically connecting to a TLS-disabled Amazon DocumentDB cluster, choose the tab for language that you want to use.

Python

The following code demonstrates how to connect to Amazon DocumentDB using Python when TLS is disabled.


1. ## Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set and specify the read preference as secondary preferred
2. client = pymongo.MongoClient('mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/?replicaSet=rs0&readPreference=secondaryPreferred')

4. ##Specify the database to be used
5. db = client.sample_database

7. ##Specify the collection to be used
8. col = db.sample_collection

10. ##Insert a single document
11. col.insert_one({'hello':'Amazon DocumentDB'})

13. ##Find the document that was previously written
14. x = col.find_one({'hello':'Amazon DocumentDB'})

16. ##Print the result to the screen
17. print(x)

19. ##Close the connection
20. client.close()

Node.js

The following code demonstrates how to connect to Amazon DocumentDB using Node.js when TLS is disabled.


1. var MongoClient = require('mongodb').MongoClient;

3. //Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set,
4. //  and specify the read preference as secondary preferred
5. var client = MongoClient.connect(
6. 'mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/sample-database?replicaSet=rs0&readPreference=secondaryPreferred',
7. {
8. useNewUrlParser: true
9. },

11. function(err, client) {
12. if(err)
13. throw err;
14. //Specify the database to be used
15. db = client.db('sample-database');

17. //Specify the collection to be used
18. col = db.collection('sample-collection');

20. //Insert a single document
21. col.insertOne({'hello':'Amazon DocumentDB'}, function(err, result){
22. //Find the document that was previously written
23. col.findOne({'hello':'Amazon DocumentDB'}, function(err, result){
24. //Print the result to the screen
25. console.log(result);

27. //Close the connection
28. client.close()
29. });
30. });
31. });

PHP

The following code demonstrates how to connect to Amazon DocumentDB using PHP when TLS is disabled.


1. <?php
2. //Include Composer's autoloader
3. require 'vendor/autoload.php';

5. //Create a MongoDB client and open connection to Amazon DocumentDB
6. $client = new MongoDB\Client("mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017");

8. //Specify the database and collection to be used
9. $col = $client->sample-database->sample-collection;

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

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

17. //Print the result to the screen
18. print_r($result);
19. ?>

Go

The following code demonstrates how to connect to Amazon DocumentDB using Go when TLS is disabled.


1. package main

3. import (
4. "context"
5. "fmt"
6. "log"
7. "time"

9. "go.mongodb.org/mongo-driver/bson"
10. "go.mongodb.org/mongo-driver/mongo"
11. "go.mongodb.org/mongo-driver/mongo/options"
12. )

14. const (
15. // Timeout operations after N seconds
16. connectTimeout  = 5
17. queryTimeout    = 30
18. username        = "<sample-user>"
19. password        = "<password>"
20. clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017"

22. // Which instances to read from
23. readPreference           = "secondaryPreferred"
24. connectionStringTemplate = "mongodb://%s:%s@%s/sample-database?replicaSet=rs0&readpreference=%s"
25. )

27. func main() {

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

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

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

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

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

50. fmt.Println("Connected to DocumentDB!")

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

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

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

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

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

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

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

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

80. if err != nil {
81. log.Fatal(err)
82. }
83. }

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

89. }

Java

The following code demonstrates how to connect to Amazon DocumentDB using Java when TLS is disabled.


1. package com.example.documentdb;

3. import com.mongodb.MongoClient;
4. import com.mongodb.MongoClientURI;
5. import com.mongodb.ServerAddress;
6. import com.mongodb.MongoException;
7. import com.mongodb.client.MongoCursor;
8. import com.mongodb.client.MongoDatabase;
9. import com.mongodb.client.MongoCollection;
10. import org.bson.Document;

13. public final class Main {
14. private Main() {
15. }
16. public static void main(String[] args) {

18. String template = "mongodb://%s:%s@%s/sample-database?replicaSet=rs0&readpreference=%s";
19. String username = "<sample-user>";
20. String password = "<password>";
21. String clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
22. String readPreference = "secondaryPreferred";
23. String connectionString = String.format(template, username, password, clusterEndpoint, readPreference);

25. MongoClientURI clientURI = new MongoClientURI(connectionString);
26. MongoClient mongoClient = new MongoClient(clientURI);

28. MongoDatabase testDB = mongoClient.getDatabase("sample-database");
29. MongoCollection<Document> numbersCollection = testDB.getCollection("sample-collection");

31. Document doc = new Document("name", "pi").append("value", 3.14159);
32. numbersCollection.insertOne(doc);

34. MongoCursor<Document> cursor = numbersCollection.find().iterator();
35. try {
36. while (cursor.hasNext()) {
37. System.out.println(cursor.next().toJson());
38. }
39. } finally {
40. cursor.close();
41. }

43. }
44. }

C# / .NET

The following code demonstrates how to connect to Amazon DocumentDB using C# / .NET when TLS is disabled.


1. using System;
2. using System.Text;
3. using System.Linq;
4. using System.Collections.Generic;
5. using System.Security.Cryptography;
6. using System.Security.Cryptography.X509Certificates;
7. using System.Net.Security;
8. using MongoDB.Driver;
9. using MongoDB.Bson;

11. namespace CSharpSample
12. {
13. class Program
14. {
15. static void Main(string[] args)
16. {
17. string template = "mongodb://{0}:{1}@{2}/sample-database?&replicaSet=rs0&readpreference={3}";
18. string username = "<sample-user>";
19. string password = "<password>";
20. string clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
21. string readPreference = "secondaryPreferred";
22. string connectionString = String.Format(template, username, password, clusterEndpoint, readPreference);

24. var settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
25. var client = new MongoClient(settings);

27. var database = client.GetDatabase("sample-database");
28. var collection = database.GetCollection<BsonDocument>("sample-collection");
29. var docToInsert = new BsonDocument { { "pi", 3.14159 } };
30. collection.InsertOne(docToInsert);
31. }
32. }
33. }

mongo shell

The following code demonstrates how to connect to and query Amazon DocumentDB using the mongo shell when TLS is disabled.

  1. Connect to Amazon DocumentDB with the mongo shell.

```

  1. mongo --host mycluster.node.us-east-1.docdb.amazonaws.com:27017 --username --password ```
  2. Insert a single document.

```

  1. db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'}) ```
  2. Find the document that was previously inserted.

```

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

R

The following code demonstrates how to connect to Amazon DocumentDB with R using mongolite (https://jeroen.github.io/mongolite/) when TLS is disabled.


1. #Include the mongolite library.
2. library(mongolite)

4. #Create a MongoDB client, open a connection to Amazon DocumentDB as a replica
5. #   set and specify the read preference as secondary preferred
6. client <- mongo(url = "mongodb://sample-user;:password@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/sample-database?readPreference=secondaryPreferred&replicaSet=rs0")

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

12. ##Find the document that was previously written
13. client$find()

Ruby

The following code demonstrates how to connect to Amazon DocumentDB with Ruby when TLS is disabled.


1. require 'mongo'
2. require 'neatjson'
3. require 'json'
4. client_host = 'mongodb://sample-cluster.node.us-east-1.docdb.amazonaws.com:27017'
5. client_options = {
6. database: 'test',
7. replica_set: 'rs0',
8. read: {:secondary_preferred => 1},
9. user: '<sample-user>',
10. password: '<password>',
11. ssl: true,
12. ssl_verify: true,
13. ssl_ca_cert: <path to 'rds-combined-ca-bundle.pem'>
14. }

16. begin
17. ##Create a MongoDB client, open a connection to Amazon DocumentDB as a
18. ##   replica set and specify the read preference as secondary preferred
19. client = Mongo::Client.new(client_host, client_options)

21. ##Insert a single document
22. x = client[:test].insert_one({"hello":"Amazon DocumentDB"})

24. ##Find the document that was previously written
25. result = client[:test].find()

27. #Print the document
28. result.each do |document|
29. puts JSON.neat_generate(document)
30. end
31. end

33. #Close the connection
34. client.close