Amazon DocumentDB
Developer Guide

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 Connections Using TLS.

Important

The certificate authority (CA) certificate for Amazon DocumentDB clusters is being updated. As of September 1, 2019, the new CA bundle (rds-combined-ca-bundle.pem) contains both the old CA certificate (rds-ca-2015-root.pem) and the new CA certificate (rds-ca-2019-root.pem).

To avoid an interruption in connectivity between your application and your Amazon DocumentDB clusters, take the following actions before February 5, 2020:

  1. Download the new CA certificate (rds-ca-2019-root.pem) and update your application to use the new CA certificate to create TLS connections to Amazon DocumentDB.

  2. Modify the instances in your Amazon DocumentDB clusters to update the server certificate.

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.

To determine the value of your tls parameter

  1. Determine which parameter group is governing your cluster. For more information, see Determining a DB Cluster's Parameter Group.

  2. Determine the value of the tls parameter in your cluster's parameter group. For more information, see Viewing Amazon DocumentDB Cluster Parameters.

After determining the value of your tls parameter, continue 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.

PythonNode.jsPHPGoJavaC# / .NETmongo shellRRuby
Python

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

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://<dbusername>:<dbpassword>@mycluster.node.us-east-1.docdb.amazonaws.com:27017/?ssl=true&ssl_ca_certs=rds-combined-ca-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred') ##Specify the database to be used db = client.test ##Specify the collection to be used col = db.myTestCollection ##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

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

var MongoClient = require('mongodb').MongoClient, f = require('util').format, fs = require('fs'); //Specify the Amazon DocumentDB cert var ca = [fs.readFileSync("rds-combined-ca-bundle.pem")]; //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://<dbusername>:<dbpassword>@mycluster.node.us-east-1.docdb.amazonaws.com:27017/test?ssl=true&replicaSet=rs0&readPreference=secondaryPreferred', { sslValidate: true, sslCA:ca, useNewUrlParser: true }, function(err, client) { if(err) throw err; //Specify the database to be used db = client.db('test'); //Specify the collection to be used col = db.collection('col'); //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

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

<?php //Include Composer's autoloader require 'vendor/autoload.php'; $SSL_DIR = "/home/ubuntu"; $SSL_FILE = "rds-combined-ca-bundle.pem"; //Specify the Amazon DocumentDB cert $ctx = stream_context_create(array( "ssl" => array( "cafile" => $SSL_DIR . "/" . $SSL_FILE, )) ); //Create a MongoDB client and open connection to Amazon DocumentDB $client = new MongoDB\Client("mongodb://<dbusername>:<dbpassword>@mycluster.node.us-east-1.docdb.amazonaws.com:27017", array("ssl" => true), array("context" => $ctx)); //Specify the database and collection to be used $col = $client->test->col; //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

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

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 ( // Path to the AWS CA file caFilePath = "rds-combined-ca-bundle.pem" // Timeout operations after N seconds connectTimeout = 5 queryTimeout = 30 username = "<dbusername>" password = "<dbpassword>" clusterEndpoint = "mycluster.node.us-east-1.docdb.amazonaws.com:27017" // Which instances to read from readPreference = "secondaryPreferred" connectionStringTemplate = "mongodb://%s:%s@%s/test?ssl=true&sslcertificateauthorityfile=%s&replicaSet=rs0&readpreference=%s" ) func main() { connectionURI := fmt.Sprintf(connectionStringTemplate, username, password, clusterEndpoint, caFilePath, 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("test").Collection("numbers") 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

When connecting to a TLS-enabled Amazon DocumentDB cluster from a Java application, your program must use the AWS-provided Certificate Authority file to validate the connection. To use the AWS 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 keystore with the CA certificate contained in the file by performing the following commands. Be sure to change the <keystorePassword> to something else.

    keytool -importcert -trustcacerts -file rds-combined-ca-bundle.pem -alias rds -keystore rds-ca-certs -storepass <keystorePassword>
  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:

    javax.net.ssl.trustStore: the file path to your newly created keystore javax.net.ssl.trustStorePassword: <keystorePassword>

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; public final class Main { private Main() { } public static void main(String[] args) { String template = "mongodb://%s:%s@%s/test?ssl=true&replicaSet=rs0&readpreference=%s"; String username = "<dbusername>"; String password = "<dbpassword>"; String clusterEndpoint = "mycluster.node.us-east-1.docdb.amazonaws.com:27017"; String readPreference = "secondaryPreferred"; String connectionString = String.format(template, username, password, clusterEndpoint, readPreference); String keystore = "rds-ca-certs"; String keystorePassword = "<keystorePassword>"; System.setProperty("javax.net.ssl.trustStore", keystore); System.setProperty("javax.net.ssl.trustStorePassword", keystorePassword); MongoClientURI clientURI = new MongoClientURI(connectionString); MongoClient mongoClient = new MongoClient(clientURI); MongoDatabase testDB = mongoClient.getDatabase("test"); MongoCollection<Document> numbersCollection = testDB.getCollection("numbers"); 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# / .NET
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}/test?ssl=true&replicaSet=rs0&readpreference={3}"; string username = "<dbusername>"; string password = "<dbpassword>"; string readPreference = "secondaryPreferred"; string connectionString = String.Format(template, username, password, clusterEndpoint, readPreference); string pathToCAFile = "<path_to_rds-combined-ca-bundle.pem>"; // ADD CA certificate to local trust store // DO this once - Maybe when your service starts X509Store localTrustStore = new X509Store(StoreName.Root); string caContentString = System.IO.File.ReadAllText(pathToCAFile); X509Certificate2 caCert = new X509Certificate2(Encoding.ASCII.GetBytes(caContentString)); try { localTrustStore.Open(OpenFlags.ReadWrite); localTrustStore.Add(caCert); } 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("test"); var collection = database.GetCollection<BsonDocument>("numbers"); var docToInsert = new BsonDocument { { "pi", 3.14159 } }; collection.InsertOne(docToInsert); } } }
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.

    mongo --ssl --host mycluster.node.us-east-1.docdb.amazonaws.com:27017 --sslCAFile rds-combined-ca-bundle.pem --username <dbusername> --password <dbpassword>
  2. Insert a single document.

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

    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.

##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://<user-name>:<password>@mycluster.cluster-ccuszbx3pn5e.us-east-1.docdb.amazonaws.com:27017/test2?ssl=true&readPreference=secondaryPreferred&replicaSet=rs0", options = ssl_options(weak_cert_validation = T, key = 'rds-combined-ca-bundle.pem')) ##Insert a single document str <- c('{"hello" : "Amazon DocumentDB"}') client$insert(str) ##Find the document that was previously written client$find()
Ruby

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

require 'mongo' require 'neatjson' require 'json' client_host = 'mongodb://mycluster.cluster-ccuszbx3pn5e.us-east-1.docdb.amazonaws.com:27017' client_options = { database: 'test', replica_set: 'rs0', mode: 'secondary_preferred', user: '<user-name>', password: '<password>', ssl: true, ssl_verify: false, ssl_ca_file: 'rds-combined-ca-bundle.pem' } 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

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.

PythonNode.jsPHPGoJavaC# / .NETmongo shellRRuby
Python

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

## 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://<dbusername>:<dbpassword>@mycluster.node.us-east-1.docdb.amazonaws.com:27017/?replicaSet=rs0&readPreference=secondaryPreferred') ##Specify the database to be used db = client.test ##Specify the collection to be used col = db.myTestCollection ##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

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

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://<dbusername>:<dbpassword>@mycluster.node.us-east-1.docdb.amazonaws.com:27017/test?replicaSet=rs0&readPreference=secondaryPreferred', { useNewUrlParser: true }, function(err, client) { if(err) throw err; //Specify the database to be used db = client.db('test'); //Specify the collection to be used col = db.collection('col'); //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

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

<?php //Include Composer's autoloader require 'vendor/autoload.php'; //Create a MongoDB client and open connection to Amazon DocumentDB $client = new MongoDB\Client("mongodb://<dbusername>:<dbpassword>@mycluster.node.us-east-1.docdb.amazonaws.com:27017"); //Specify the database and collection to be used $col = $client->test->col; //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

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

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 = "<dbusername>" password = "<dbpassword>" clusterEndpoint = "mycluster.node.us-east-1.docdb.amazonaws.com:27017" // Which instances to read from readPreference = "secondaryPreferred" connectionStringTemplate = "mongodb://%s:%s@%s/test?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("test").Collection("numbers") 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

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

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/test?replicaSet=rs0&readpreference=%s"; String username = "<dbusername>"; String password = "<dbpassword>"; String clusterEndpoint = "mycluster.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("test"); MongoCollection<Document> numbersCollection = testDB.getCollection("numbers"); 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# / .NET
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}/test?&replicaSet=rs0&readpreference={3}"; string username = "<dbusername>"; string password = "<dbpassword>"; string clusterEndpoint = "mycluster.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("test"); var collection = database.GetCollection<BsonDocument>("numbers"); var docToInsert = new BsonDocument { { "pi", 3.14159 } }; collection.InsertOne(docToInsert); } } }
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.

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

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

    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.

##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://<user-name>:<password>@mycluster.cluster-ccuszbx3pn5e.us-east-1.docdb.amazonaws.com:27017/test2?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

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

require 'mongo' require 'neatjson' require 'json' client_host = 'mongodb://mycluster.cluster-ccuszbx3pn5e.us-east-1.docdb.amazonaws.com:27017' client_options = { database: 'test', replica_set: 'rs0', mode: 'secondary_preferred', user: '<user-name>', password: '<password>', } 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