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.

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

    2. In the left navigation pane, choose Clusters.

    3. In the list of clusters, select the name of your cluster.

    4. 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. ]
  2. Determine the value of the tls parameter in your cluster’s parameter group.

    1. In the navigation pane, choose Parameter groups.

    2. In the Cluster parameter groups window, select your cluster parameter group.

    3. 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. ```
  5. Output from this operation looks something like the following:
  6. ```
  7. {
  8. "Parameters": [
  9. {
  10. "ParameterName": "profiler_threshold_ms",
  11. "ParameterValue": "100",
  12. "Description": "Operations longer than profiler_threshold_ms will be logged",
  13. "Source": "system",
  14. "ApplyType": "dynamic",
  15. "DataType": "integer",
  16. "AllowedValues": "50-2147483646",
  17. "IsModifiable": true,
  18. "ApplyMethod": "pending-reboot"
  19. },
  20. {
  21. "ParameterName": "tls",
  22. "ParameterValue": "disabled",
  23. "Description": "Config to enable/disable TLS",
  24. "Source": "user",
  25. "ApplyType": "static",
  26. "DataType": "string",
  27. "AllowedValues": "disabled,enabled",
  28. "IsModifiable": true,
  29. "ApplyMethod": "pending-reboot"
  30. }
  31. ]
  32. }
  33. ```

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
  3. ##Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set and specify the read preference as secondary preferred
  4. 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')
  5. ##Specify the database to be used
  6. db = client.sample_database
  7. ##Specify the collection to be used
  8. col = db.sample_collection
  9. ##Insert a single document
  10. col.insert_one({'hello':'Amazon DocumentDB'})
  11. ##Find the document that was previously written
  12. x = col.find_one({'hello':'Amazon DocumentDB'})
  13. ##Print the result to the screen
  14. print(x)
  15. ##Close the connection
  16. 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');
  4. //Specify the Amazon DocumentDB cert
  5. var ca = [fs.readFileSync("rds-combined-ca-bundle.pem")];
  6. //Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set,
  7. // and specify the read preference as secondary preferred
  8. var client = MongoClient.connect(
  9. 'mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/sample-database?ssl=true&replicaSet=rs0&readPreference=secondaryPreferred',
  10. {
  11. sslValidate: true,
  12. sslCA:ca,
  13. useNewUrlParser: true
  14. },
  15. function(err, client) {
  16. if(err)
  17. throw err;
  18. //Specify the database to be used
  19. db = client.db('sample-database');
  20. //Specify the collection to be used
  21. col = db.collection('sample-collection');
  22. //Insert a single document
  23. col.insertOne({'hello':'Amazon DocumentDB'}, function(err, result){
  24. //Find the document that was previously written
  25. col.findOne({'hello':'Amazon DocumentDB'}, function(err, result){
  26. //Print the result to the screen
  27. console.log(result);
  28. //Close the connection
  29. client.close()
  30. });
  31. });
  32. });

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';
  4. $SSL_DIR = "/home/ubuntu";
  5. $SSL_FILE = "rds-combined-ca-bundle.pem";
  6. //Specify the Amazon DocumentDB cert
  7. $ctx = stream_context_create(array(
  8. "ssl" => array(
  9. "cafile" => $SSL_DIR . "/" . $SSL_FILE,
  10. ))
  11. );
  12. //Create a MongoDB client and open connection to Amazon DocumentDB
  13. $client = new MongoDB\Client("mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017", array("ssl" => true), array("context" => $ctx));
  14. //Specify the database and collection to be used
  15. $col = $client->sample-database->sample-collection;
  16. //Insert a single document
  17. $result = $col->insertOne( [ 'hello' => 'Amazon DocumentDB'] );
  18. //Find the document that was previously written
  19. $result = $col->findOne(array('hello' => 'Amazon DocumentDB'));
  20. //Print the result to the screen
  21. print_r($result);
  22. ?>

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
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "time"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/mongo"
  9. "go.mongodb.org/mongo-driver/mongo/options"
  10. "io/ioutil"
  11. "crypto/tls"
  12. "crypto/x509"
  13. "errors"
  14. )
  15. const (
  16. // Path to the AWS CA file
  17. caFilePath = "rds-combined-ca-bundle.pem"
  18. // Timeout operations after N seconds
  19. connectTimeout = 5
  20. queryTimeout = 30
  21. username = "<sample-user>"
  22. password = "<password>"
  23. clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017"
  24. // Which instances to read from
  25. readPreference = "secondaryPreferred"
  26. connectionStringTemplate = "mongodb://%s:%s@%s/sample-database?ssl=true&replicaSet=rs0&readpreference=%s"
  27. )
  28. func main() {
  29. connectionURI := fmt.Sprintf(connectionStringTemplate, username, password, clusterEndpoint, readPreference)
  30. tlsConfig, err := getCustomTLSConfig(caFilePath)
  31. if err != nil {
  32. log.Fatalf("Failed getting TLS configuration: %v", err)
  33. }
  34. client, err := mongo.NewClient(options.Client().ApplyURI(connectionURI).SetTLSConfig(tlsConfig))
  35. if err != nil {
  36. log.Fatalf("Failed to create client: %v", err)
  37. }
  38. ctx, cancel := context.WithTimeout(context.Background(), connectTimeout*time.Second)
  39. defer cancel()
  40. err = client.Connect(ctx)
  41. if err != nil {
  42. log.Fatalf("Failed to connect to cluster: %v", err)
  43. }
  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. }
  49. fmt.Println("Connected to DocumentDB!")
  50. collection := client.Database("sample-database").Collection("sample-collection")
  51. ctx, cancel = context.WithTimeout(context.Background(), queryTimeout*time.Second)
  52. defer cancel()
  53. res, err := collection.InsertOne(ctx, bson.M{"name": "pi", "value": 3.14159})
  54. if err != nil {
  55. log.Fatalf("Failed to insert document: %v", err)
  56. }
  57. id := res.InsertedID
  58. log.Printf("Inserted document ID: %s", id)
  59. ctx, cancel = context.WithTimeout(context.Background(), queryTimeout*time.Second)
  60. defer cancel()
  61. cur, err := collection.Find(ctx, bson.D{})
  62. if err != nil {
  63. log.Fatalf("Failed to run find query: %v", err)
  64. }
  65. defer cur.Close(ctx)
  66. for cur.Next(ctx) {
  67. var result bson.M
  68. err := cur.Decode(&result)
  69. log.Printf("Returned: %v", result)
  70. if err != nil {
  71. log.Fatal(err)
  72. }
  73. }
  74. if err := cur.Err(); err != nil {
  75. log.Fatal(err)
  76. }
  77. }
  78. func getCustomTLSConfig(caFile string) (*tls.Config, error) {
  79. tlsConfig := new(tls.Config)
  80. certs, err := ioutil.ReadFile(caFile)
  81. if err != nil {
  82. return tlsConfig, err
  83. }
  84. tlsConfig.RootCAs = x509.NewCertPool()
  85. ok := tlsConfig.RootCAs.AppendCertsFromPEM(certs)
  86. if !ok {
  87. return tlsConfig, errors.New("Failed parsing pem file")
  88. }
  89. return tlsConfig, nil
  90. }

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=<truststorePassword>
    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=<truststorePassword>
    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
  3. 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: <truststore>
    2. javax.net.ssl.trustStorePassword: <truststorePassword>
  4. 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) {
  5. String template = "mongodb://%s:%s@%s/sample-database?ssl=true&replicaSet=rs0&readpreference=%s";
  6. String username = "<sample-user>";
  7. String password = "<password>";
  8. String clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
  9. String readPreference = "secondaryPreferred";
  10. String connectionString = String.format(template, username, password, clusterEndpoint, readPreference);
  11. String truststore = "<truststore>";
  12. String truststorePassword = "<truststorePassword>";
  13. System.setProperty("javax.net.ssl.trustStore", truststore);
  14. System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
  15. MongoClientURI clientURI = new MongoClientURI(connectionString);
  16. MongoClient mongoClient = new MongoClient(clientURI);
  17. MongoDatabase testDB = mongoClient.getDatabase("sample-database");
  18. MongoCollection<Document> numbersCollection = testDB.getCollection("sample-collection");
  19. Document doc = new Document("name", "pi").append("value", 3.14159);
  20. numbersCollection.insertOne(doc);
  21. MongoCursor<Document> cursor = numbersCollection.find().iterator();
  22. try {
  23. while (cursor.hasNext()) {
  24. System.out.println(cursor.next().toJson());
  25. }
  26. } finally {
  27. cursor.close();
  28. }
  29. }
  30. }
  31. ```

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;
  10. namespace DocDB
  11. {
  12. class Program
  13. {
  14. static void Main(string[] args)
  15. {
  16. string template = "mongodb://{0}:{1}@{2}/sample-database?ssl=true&replicaSet=rs0&readpreference={3}";
  17. string username = "<sample-user>";
  18. string password = "<password>";
  19. string readPreference = "secondaryPreferred";
  20. string clusterEndpoint="sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
  21. string connectionString = String.Format(template, username, password, clusterEndpoint, readPreference);
  22. string pathToCAFile = "<path_to_rds-combined-ca-bundle.p7b_file>";
  23. // ADD CA certificate to local trust store
  24. // DO this once - Maybe when your service starts
  25. X509Store localTrustStore = new X509Store(StoreName.Root);
  26. X509Certificate2Collection certificateCollection = new X509Certificate2Collection();
  27. certificateCollection.Import(pathToCAFile);
  28. try
  29. {
  30. localTrustStore.Open(OpenFlags.ReadWrite);
  31. localTrustStore.AddRange(certificateCollection);
  32. }
  33. catch (Exception ex)
  34. {
  35. Console.WriteLine("Root certificate import failed: " + ex.Message);
  36. throw;
  37. }
  38. finally
  39. {
  40. localTrustStore.Close();
  41. }
  42. var settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
  43. var client = new MongoClient(settings);
  44. var database = client.GetDatabase("sample-database");
  45. var collection = database.GetCollection<BsonDocument>("sample-collection");
  46. var docToInsert = new BsonDocument { { "pi", 3.14159 } };
  47. collection.InsertOne(docToInsert);
  48. }
  49. }
  50. }

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 <sample-user> --password <password>
  2. Insert a single document.

    1. db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
  3. 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)
  3. mongourl <- paste("mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/test2?ssl=true&",
  4. "readPreference=secondaryPreferred&replicaSet=rs0", sep="")
  5. #Create a MongoDB client, open a connection to Amazon DocumentDB as a replica
  6. # set and specify the read preference as secondary preferred
  7. client <- mongo(url = mongo(url = mongourl, options = ssl_options(weak_cert_validation = F, ca = <path to 'rds-combined-ca-bundle.pem'>))
  8. #Insert a single document
  9. str <- c('{"hello" : "Amazon DocumentDB"}')
  10. client$insert(str)
  11. #Find the document that was previously written
  12. 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. }
  15. begin
  16. ##Create a MongoDB client, open a connection to Amazon DocumentDB as a
  17. ## replica set and specify the read preference as secondary preferred
  18. client = Mongo::Client.new(client_host, client_options)
  19. ##Insert a single document
  20. x = client[:test].insert_one({"hello":"Amazon DocumentDB"})
  21. ##Find the document that was previously written
  22. result = client[:test].find()
  23. #Print the document
  24. result.each do |document|
  25. puts JSON.neat_generate(document)
  26. end
  27. end
  28. #Close the connection
  29. 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')
  3. ##Specify the database to be used
  4. db = client.sample_database
  5. ##Specify the collection to be used
  6. col = db.sample_collection
  7. ##Insert a single document
  8. col.insert_one({'hello':'Amazon DocumentDB'})
  9. ##Find the document that was previously written
  10. x = col.find_one({'hello':'Amazon DocumentDB'})
  11. ##Print the result to the screen
  12. print(x)
  13. ##Close the connection
  14. 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;
  2. //Create a MongoDB client, open a connection to Amazon DocumentDB as a replica set,
  3. // and specify the read preference as secondary preferred
  4. var client = MongoClient.connect(
  5. 'mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/sample-database?replicaSet=rs0&readPreference=secondaryPreferred',
  6. {
  7. useNewUrlParser: true
  8. },
  9. function(err, client) {
  10. if(err)
  11. throw err;
  12. //Specify the database to be used
  13. db = client.db('sample-database');
  14. //Specify the collection to be used
  15. col = db.collection('sample-collection');
  16. //Insert a single document
  17. col.insertOne({'hello':'Amazon DocumentDB'}, function(err, result){
  18. //Find the document that was previously written
  19. col.findOne({'hello':'Amazon DocumentDB'}, function(err, result){
  20. //Print the result to the screen
  21. console.log(result);
  22. //Close the connection
  23. client.close()
  24. });
  25. });
  26. });

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';
  4. //Create a MongoDB client and open connection to Amazon DocumentDB
  5. $client = new MongoDB\Client("mongodb://<sample-user>:<password>@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017");
  6. //Specify the database and collection to be used
  7. $col = $client->sample-database->sample-collection;
  8. //Insert a single document
  9. $result = $col->insertOne( [ 'hello' => 'Amazon DocumentDB'] );
  10. //Find the document that was previously written
  11. $result = $col->findOne(array('hello' => 'Amazon DocumentDB'));
  12. //Print the result to the screen
  13. print_r($result);
  14. ?>

Go

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

  1. package main
  2. import (
  3. "context"
  4. "fmt"
  5. "log"
  6. "time"
  7. "go.mongodb.org/mongo-driver/bson"
  8. "go.mongodb.org/mongo-driver/mongo"
  9. "go.mongodb.org/mongo-driver/mongo/options"
  10. )
  11. const (
  12. // Timeout operations after N seconds
  13. connectTimeout = 5
  14. queryTimeout = 30
  15. username = "<sample-user>"
  16. password = "<password>"
  17. clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017"
  18. // Which instances to read from
  19. readPreference = "secondaryPreferred"
  20. connectionStringTemplate = "mongodb://%s:%s@%s/sample-database?replicaSet=rs0&readpreference=%s"
  21. )
  22. func main() {
  23. connectionURI := fmt.Sprintf(connectionStringTemplate, username, password, clusterEndpoint, readPreference)
  24. client, err := mongo.NewClient(options.Client().ApplyURI(connectionURI))
  25. if err != nil {
  26. log.Fatalf("Failed to create client: %v", err)
  27. }
  28. ctx, cancel := context.WithTimeout(context.Background(), connectTimeout*time.Second)
  29. defer cancel()
  30. err = client.Connect(ctx)
  31. if err != nil {
  32. log.Fatalf("Failed to connect to cluster: %v", err)
  33. }
  34. // Force a connection to verify our connection string
  35. err = client.Ping(ctx, nil)
  36. if err != nil {
  37. log.Fatalf("Failed to ping cluster: %v", err)
  38. }
  39. fmt.Println("Connected to DocumentDB!")
  40. collection := client.Database("sample-database").Collection("sample-collection")
  41. ctx, cancel = context.WithTimeout(context.Background(), queryTimeout*time.Second)
  42. defer cancel()
  43. res, err := collection.InsertOne(ctx, bson.M{"name": "pi", "value": 3.14159})
  44. if err != nil {
  45. log.Fatalf("Failed to insert document: %v", err)
  46. }
  47. id := res.InsertedID
  48. log.Printf("Inserted document ID: %s", id)
  49. ctx, cancel = context.WithTimeout(context.Background(), queryTimeout*time.Second)
  50. defer cancel()
  51. cur, err := collection.Find(ctx, bson.D{})
  52. if err != nil {
  53. log.Fatalf("Failed to run find query: %v", err)
  54. }
  55. defer cur.Close(ctx)
  56. for cur.Next(ctx) {
  57. var result bson.M
  58. err := cur.Decode(&result)
  59. log.Printf("Returned: %v", result)
  60. if err != nil {
  61. log.Fatal(err)
  62. }
  63. }
  64. if err := cur.Err(); err != nil {
  65. log.Fatal(err)
  66. }
  67. }

Java

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

  1. package com.example.documentdb;
  2. import com.mongodb.MongoClient;
  3. import com.mongodb.MongoClientURI;
  4. import com.mongodb.ServerAddress;
  5. import com.mongodb.MongoException;
  6. import com.mongodb.client.MongoCursor;
  7. import com.mongodb.client.MongoDatabase;
  8. import com.mongodb.client.MongoCollection;
  9. import org.bson.Document;
  10. public final class Main {
  11. private Main() {
  12. }
  13. public static void main(String[] args) {
  14. String template = "mongodb://%s:%s@%s/sample-database?replicaSet=rs0&readpreference=%s";
  15. String username = "<sample-user>";
  16. String password = "<password>";
  17. String clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
  18. String readPreference = "secondaryPreferred";
  19. String connectionString = String.format(template, username, password, clusterEndpoint, readPreference);
  20. MongoClientURI clientURI = new MongoClientURI(connectionString);
  21. MongoClient mongoClient = new MongoClient(clientURI);
  22. MongoDatabase testDB = mongoClient.getDatabase("sample-database");
  23. MongoCollection<Document> numbersCollection = testDB.getCollection("sample-collection");
  24. Document doc = new Document("name", "pi").append("value", 3.14159);
  25. numbersCollection.insertOne(doc);
  26. MongoCursor<Document> cursor = numbersCollection.find().iterator();
  27. try {
  28. while (cursor.hasNext()) {
  29. System.out.println(cursor.next().toJson());
  30. }
  31. } finally {
  32. cursor.close();
  33. }
  34. }
  35. }

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;
  10. namespace CSharpSample
  11. {
  12. class Program
  13. {
  14. static void Main(string[] args)
  15. {
  16. string template = "mongodb://{0}:{1}@{2}/sample-database?&replicaSet=rs0&readpreference={3}";
  17. string username = "<sample-user>";
  18. string password = "<password>";
  19. string clusterEndpoint = "sample-cluster.node.us-east-1.docdb.amazonaws.com:27017";
  20. string readPreference = "secondaryPreferred";
  21. string connectionString = String.Format(template, username, password, clusterEndpoint, readPreference);
  22. var settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
  23. var client = new MongoClient(settings);
  24. var database = client.GetDatabase("sample-database");
  25. var collection = database.GetCollection<BsonDocument>("sample-collection");
  26. var docToInsert = new BsonDocument { { "pi", 3.14159 } };
  27. collection.InsertOne(docToInsert);
  28. }
  29. }
  30. }

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 <sample-user> --password <password>
  2. Insert a single document.

    1. db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
  3. 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)
  3. #Create a MongoDB client, open a connection to Amazon DocumentDB as a replica
  4. # set and specify the read preference as secondary preferred
  5. client <- mongo(url = "mongodb://sample-user;:password@sample-cluster.node.us-east-1.docdb.amazonaws.com:27017/sample-database?readPreference=secondaryPreferred&replicaSet=rs0")
  6. ##Insert a single document
  7. str <- c('{"hello" : "Amazon DocumentDB"}')
  8. client$insert(str)
  9. ##Find the document that was previously written
  10. 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. }
  15. begin
  16. ##Create a MongoDB client, open a connection to Amazon DocumentDB as a
  17. ## replica set and specify the read preference as secondary preferred
  18. client = Mongo::Client.new(client_host, client_options)
  19. ##Insert a single document
  20. x = client[:test].insert_one({"hello":"Amazon DocumentDB"})
  21. ##Find the document that was previously written
  22. result = client[:test].find()
  23. #Print the document
  24. result.each do |document|
  25. puts JSON.neat_generate(document)
  26. end
  27. end
  28. #Close the connection
  29. client.close