Programmgesteuertes Herstellen einer Verbindung zu Amazon DocumentDB - Amazon DocumentDB

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Programmgesteuertes Herstellen einer Verbindung zu Amazon DocumentDB

Dieser Abschnitt enthält Codebeispiele, die zeigen, wie Sie mithilfe verschiedener Sprachen eine Verbindung zu Amazon DocumentDB (mit MongoDB-Kompatibilität) herstellen können. Die Beispiele sind in zwei Abschnitte unterteilt, je nachdem, ob Sie eine Verbindung zu einem Cluster herstellen, für den Transport Layer Security (TLS) aktiviert oder deaktiviert ist. TLSIst standardmäßig auf Amazon DocumentDB-Clustern aktiviert. Sie können es jedoch ausschalten, TLS wenn Sie möchten. Weitere Informationen finden Sie unter Verschlüsseln von Daten während der Übertragung.

Wenn Sie versuchen, von außerhalb des Clusters, VPC in dem sich Ihr Cluster befindet, eine Verbindung zu Ihrer Amazon DocumentDB herzustellen, finden Sie weitere Informationen unter. Verbindung zu einem Amazon DocumentDB-Cluster von außerhalb eines Amazon herstellen VPC

Bevor Sie eine Verbindung zu Ihrem Cluster herstellen, müssen Sie wissen, ob die Option auf dem Cluster aktiviert TLS ist. Der nächste Abschnitt zeigt Ihnen, wie Sie den Wert des Parameters tls Ihres Clusters mit der AWS Management Console oder der AWS CLI bestimmen können. Danach können Sie fortfahren, indem Sie das entsprechende Codebeispiel anwenden.

Ermitteln Sie den Wert Ihres tls Parameters

Die Feststellung, ob Ihr Cluster TLS aktiviert wurde, ist ein zweistufiger Prozess, den Sie entweder mit AWS Management Console oder AWS CLI durchführen können.

  1. Bestimmen Sie, welche Parametergruppe Ihren Cluster steuert.

    Using the AWS Management Console
    1. Melden Sie sich bei der AWS Management Console an und öffnen Sie die Amazon DocumentDB DocumentDB-Konsole unter https://console.aws.amazon.com/docdb.

    2. Wählen Sie im linken Navigationsbereich die Option Cluster aus.

    3. Wählen Sie in der Liste der Cluster den Namen des Clusters aus.

    4. Auf der anschließend angezeigten Seite werden die Details des von Ihnen ausgewählten Clusters angezeigt. Scrollen Sie nach unten zu Cluster details (Clusterdetails). Sie finden den Namen der Parametergruppe unten in diesem Abschnitt unterhalb von Cluster parameter group (Cluster-Parametergruppe).

    Using the AWS CLI

    Der folgende AWS CLI Code bestimmt, welcher Parameter Ihren Cluster steuert. Ersetzen Sie sample-cluster durch den Namen Ihres Clusters.

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

    Die Ausgabe dieser Operation sieht in etwa wie folgt aus:

    [ [ "sample-cluster", "sample-parameter-group" ] ]
  2. Bestimmen Sie den Wert des Parameters tls in der Parametergruppe Ihres Clusters.

    Using the AWS Management Console
    1. Wählen Sie im Navigationsbereich Parameter groups (Parametergruppen) aus.

    2. Wählen Sie im Fenster Cluster parameter groups (Cluster-Parametergruppen) Ihre Cluster-Parametergruppe aus.

    3. Auf der Ergebnisseite werden die Parameter der Cluster-Parametergruppe angezeigt. Hier können Sie den Wert des tls-Parameters sehen. Informationen zum Ändern dieses Parameters finden Sie unter Amazon DocumentDB-Cluster-Parametergruppen ändern.

    Using the AWS CLI

    Sie können den describe-db-cluster-parameters AWS CLI Befehl verwenden, um die Details der Parameter in Ihrer Cluster-Parametergruppe anzuzeigen.

    • --describe-db-cluster-parameters— Um alle Parameter innerhalb einer Parametergruppe und ihre Werte aufzulisten.

      • --db-cluster-parameter-group name – Erforderlich. Der Name Ihrer Cluster-Parametergruppe.

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

    Die Ausgabe dieser Operation sieht in etwa wie folgt aus:

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

    Amazon DocumentDB unterstützt FIPS 140-3 Endpunkte, beginnend mit Amazon DocumentDB 5.0-Clustern (Engine-Version 3.0.3727) in diesen Regionen: ca-central-1, us-west-2, us-east-1, us-east-2, -1, -1. us-gov-east us-gov-west

Nachdem Sie den Wert des tls-Parameters bestimmt haben, fahren Sie mit dem Herstellen einer Verbindung zu Ihrem Cluster fort, indem Sie eines der Codebeispiele in den folgenden Abschnitten verwenden.

TLSVerbindung herstellen mit aktiviert

Um ein Codebeispiel für die programmgesteuerte Verbindung zu einem Amazon TLS DocumentDB-Cluster mit aktiviertem Amazon DocumentDB-Cluster anzuzeigen, wählen Sie die entsprechende Registerkarte für die Sprache, die Sie verwenden möchten.

Um Daten während der Übertragung zu verschlüsseln, laden Sie den öffentlichen Schlüssel für Amazon DocumentDB global-bundle.pem mit dem folgenden Vorgang herunter.

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

Wenn Ihre Anwendung unter Microsoft Windows läuft und eine PKCS7 Datei benötigt, können Sie das PKCS7 Zertifikatspaket herunterladen. Dieses Paket enthält sowohl die Zwischen- als auch die Stammzertifikate unter https://truststore.pki.rds.amazonaws.com/global/global-bundle.p7b.

Python

Der folgende Code zeigt, wie Sie mithilfe von Python eine Verbindung zu Amazon DocumentDB herstellen, wenn TLS es aktiviert ist.

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

Der folgende Code zeigt, wie Sie mithilfe von Node.js eine Verbindung zu Amazon DocumentDB herstellen, wenn diese Option aktiviert TLS ist.

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

Der folgende Code zeigt, wie eine Verbindung zu Amazon DocumentDB hergestellt wird, indem PHP When aktiviert TLS ist.

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

Der folgende Code zeigt, wie Sie mit Go eine Verbindung zu Amazon DocumentDB herstellen, wenn TLS es aktiviert ist.

Anmerkung

Ab Version 1.2.1 verwendet der MongoDB Go Driver nur das erste CA-Serverzertifikat, das in sslcertificateauthorityfile gefunden wurde. Der folgende Beispielcode behebt diese Einschränkung, indem alle Serverzertifikate, die in gefunden wurden, manuell sslcertificateauthorityfile an eine benutzerdefinierte TLS Konfiguration angehängt werden, die bei der Client-Erstellung verwendet wurde.

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

Wenn Sie von einer Java-Anwendung aus TLS eine Verbindung zu einem Amazon DocumentDB-Cluster herstellen, muss Ihr Programm die von AWS-bereitgestellte Zertifizierungsstelle (CA) -Datei verwenden, um die Verbindung zu validieren. Gehen Sie wie folgt vor, um das Amazon RDS CA-Zertifikat zu verwenden:

  1. Laden Sie die Amazon RDS CA-Datei von herunter https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem.

  2. Erstellen Sie einen Vertrauensspeicher mit dem in der Datei enthaltenen CA-Zertifikat, indem Sie die folgenden Befehle ausführen. Achten Sie darauf, das zu ändern <truststorePassword> zu etwas anderem. Wenn Sie auf einen Vertrauensspeicher zugreifen, der sowohl das alte CA-Zertifikat (rds-ca-2015-root.pem) als auch das neue CA-Zertifikat (rds-ca-2019-root.pem) enthält, können Sie das Zertifikat-Bundle in den Vertrauensspeicher importieren.

    Nachfolgend finden Sie ein Beispiel-Shell-Skript, das das Zertifikatpaket in einen Trust Store auf einem Linux-Betriebssystem importiert. Ersetzen Sie im folgenden Beispiel jedes user input placeholder mit Ihren eigenen Informationen. Vor allem, wo auch immer das Beispielverzeichnis ist“mydir"befindet sich im Skript. Ersetzen Sie es durch ein Verzeichnis, das Sie für diese Aufgabe erstellt haben.

    mydir=/tmp/certs truststore=${mydir}/rds-truststore.jks storepassword=<truststorePassword> 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

    Es folgt ein Beispiel für ein Shell-Skript, das das Zertifikatspaket in einen Vertrauensspeicher unter macOS importiert.

    mydir=/tmp/certs truststore=${mydir}/rds-truststore.jks storepassword=<truststorePassword> 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
  3. Verwenden Sie das keystore in Ihrem Programm, indem Sie die folgenden Systemeigenschaften in Ihrer Anwendung festlegen, bevor Sie eine Verbindung zum Amazon DocumentDB-Cluster herstellen.

    javax.net.ssl.trustStore: <truststore> javax.net.ssl.trustStorePassword: <truststorePassword>
  4. Der folgende Code zeigt, wie Sie mithilfe von Java eine Verbindung zu Amazon DocumentDB herstellen, wenn TLS es aktiviert ist.

    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 = "<truststorePassword>"; 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# / .NET

Der folgende Code zeigt, wie Sie mit C#/eine Verbindung zu Amazon DocumentDB herstellen. NETwann TLS ist aktiviert.

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); } } }
mongo shell

Der folgende Code zeigt, wie Sie mit der Mongo-Shell eine Verbindung zu Amazon DocumentDB herstellen und diese abfragen, wenn sie aktiviert TLS ist.

  1. Stellen Sie mit der Mongo-Shell eine Connect zu Amazon DocumentDB her. Wenn Sie eine Mongo-Shell-Version vor 4.2 verwenden, verwenden Sie den folgenden Code, um eine Verbindung herzustellen.

    mongo --ssl --host sample-cluster.node.us-east-1.docdb.amazonaws.com:27017 --sslCAFile global-bundle.pem --username <sample-user> --password <password>

    Wenn Sie eine Version verwenden, die 4.2 oder höher ist, verwenden Sie den folgenden Code, um eine Verbindung herzustellen. Wiederholbare Schreibvorgänge werden in DocumentDB nicht unterstützt. AWS Wenn Sie eine ältere Mongo-Shell (nicht Mongosh) verwenden, nehmen Sie den retryWrites=false Befehl nicht in eine Codezeichenfolge auf. Standardmäßig sind wiederholbare Schreibvorgänge deaktiviert. retryWrites=falseDas Einschließen kann zu einem Fehler bei normalen Lesebefehlen führen.

    mongo --tls --host sample-cluster.node.us-east-1.docdb.amazonaws.com:27017 --tlsCAFile global-bundle.pem --username <sample-user> --password <password>
  2. Fügen Sie ein einzelnes Dokument ein.

    db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
  3. Suchen Sie das Dokument, das zuvor eingefügt wurde.

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

Der folgende Code zeigt, wie Sie mit R mithilfe von mongolite (https://jeroen.github.io/mongolite/) eine Verbindung zu Amazon DocumentDB herstellen, wenn TLS es aktiviert ist.

#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

Der folgende Code zeigt, wie Sie mit Ruby eine Verbindung zu Amazon DocumentDB herstellen, wenn TLS es aktiviert ist.

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

Verbindung herstellen mit deaktiviert TLS

Um ein Codebeispiel für die programmgesteuerte Verbindung zu einem Amazon TLS DocumentDB-Cluster mit deaktiviertem Amazon DocumentDB-Cluster anzuzeigen, wählen Sie die Registerkarte für die Sprache, die Sie verwenden möchten.

Python

Der folgende Code zeigt, wie Sie mithilfe von Python eine Verbindung zu Amazon DocumentDB herstellen, wenn TLS es deaktiviert ist.

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

Der folgende Code zeigt, wie Sie mithilfe von Node.js eine Verbindung zu Amazon DocumentDB herstellen, wenn TLS es deaktiviert ist.

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

Der folgende Code zeigt, wie eine Verbindung zu Amazon DocumentDB hergestellt werden kannPHP, wenn deaktiviert TLS ist.

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

Der folgende Code zeigt, wie Sie mit Go eine Verbindung zu Amazon DocumentDB herstellen, wenn TLS es deaktiviert ist.

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

Der folgende Code zeigt, wie Sie mithilfe von Java eine Verbindung zu Amazon DocumentDB herstellen, wenn TLS es deaktiviert ist.

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# / .NET

Der folgende Code zeigt, wie Sie mit C#/eine Verbindung zu Amazon DocumentDB herstellen. NETwann TLS ist deaktiviert.

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); } } }
mongo shell

Der folgende Code zeigt, wie Sie mit der Mongo-Shell eine Verbindung zu Amazon DocumentDB herstellen und diese abfragen, wenn sie deaktiviert TLS ist.

  1. Stellen Sie mit der Mongo-Shell eine Connect zu Amazon DocumentDB her.

    mongo --host mycluster.node.us-east-1.docdb.amazonaws.com:27017 --username <sample-user> --password <password>
  2. Fügen Sie ein einzelnes Dokument ein.

    db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
  3. Suchen Sie das Dokument, das zuvor eingefügt wurde.

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

Der folgende Code zeigt, wie Sie mit R mithilfe von mongolite (https://jeroen.github.io/mongolite/) eine Verbindung zu Amazon DocumentDB herstellen, wenn TLS es deaktiviert ist.

#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

Der folgende Code zeigt, wie Sie mit Ruby eine Verbindung zu Amazon DocumentDB herstellen, wenn Ruby deaktiviert TLS ist.

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