Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.
Menghubungkan secara terprogram ke Amazon DocumentDB
Bagian ini berisi contoh kode yang menunjukkan cara menghubungkan ke Amazon DocumentDB (dengan kompatibilitas MongoDB) menggunakan beberapa bahasa yang berbeda. Contoh dipisahkan menjadi dua bagian berdasarkan apakah Anda terhubung ke cluster yang memiliki Transport Layer Security (TLS) diaktifkan atau dinonaktifkan. Secara default, TLS diaktifkan pada cluster Amazon DocumentDB. Namun, Anda dapat mematikan TLS jika Anda mau. Untuk informasi selengkapnya, lihat Mengenkripsi data dalam perjalanan.
Jika Anda mencoba untuk terhubung ke Amazon DocumentDB Anda dari VPC luar tempat klaster Anda berada, silakan lihat. Menghubungkan ke cluster Amazon DocumentDB dari luar Amazon VPC
Sebelum Anda terhubung ke cluster Anda, Anda harus tahu TLS apakah diaktifkan pada cluster. Bagian berikutnya menunjukkan kepada Anda bagaimana untuk menentukan nilai parameter tls
klaster Anda menggunakan AWS Management Console atau AWS CLI. Setelah itu, Anda dapat melanjutkan dengan menemukan dan menerapkan contoh kode yang sesuai.
Topik
Menentukan nilai tls
parameter Anda
Menentukan apakah klaster Anda telah TLS diaktifkan adalah proses dua langkah yang dapat Anda lakukan menggunakan AWS Management Console atau AWS CLI.
-
Tentukan grup parameter mana yang mengatur cluster Anda.
- Using the AWS Management Console
-
-
Pada panel navigasi sebelah kiri, pilih Klaster.
-
Dalam daftar klaster, pilih nama klaster Anda.
-
Halaman yang dihasilkan menunjukkan detail klaster yang Anda pilih. Gulir ke bawah ke Detail klaster. Di bagian bawah bagian tersebut, temukan nama grup parameter di bawah Grup parameter klaster.
- Using the AWS CLI
-
AWS CLI Kode berikut menentukan parameter mana yang mengatur cluster Anda. Pastikan Anda mengganti
sample-cluster
dengan nama klaster Anda.aws docdb describe-db-clusters \ --db-cluster-identifier
sample-cluster
\ --query 'DBClusters[*].[DBClusterIdentifier,DBClusterParameterGroup]'Keluaran dari operasi ini terlihat seperti berikut ini:
[ [ "sample-cluster", "sample-parameter-group" ] ]
-
Tentukan nilai
tls
parameter dalam grup parameter cluster Anda.- Using the AWS Management Console
-
-
Di panel navigasi, pilih Grup parameter.
-
Di jendela grup parameter Cluster, pilih grup parameter cluster Anda.
-
Halaman yang dihasilkan menunjukkan parameter grup parameter klaster Anda. Anda dapat melihat nilai dari parameter
tls
di sini. Untuk informasi tentang memodifikasi parameter ini, lihat Memodifikasi grup parameter cluster Amazon DocumentDB.
-
- Using the AWS CLI
-
Anda dapat menggunakan
describe-db-cluster-parameters
AWS CLI perintah untuk melihat detail parameter dalam grup parameter cluster Anda.-
--describe-db-cluster-parameters
— Untuk membuat daftar semua parameter di dalam grup parameter dan nilainya.-
--db-cluster-parameter-group name
— Diperlukan. Nama grup parameter klaster Anda.
-
aws docdb describe-db-cluster-parameters \ --db-cluster-parameter-group-name sample-parameter-group
Keluaran dari operasi ini terlihat seperti berikut ini:
{ "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" } ] }
catatan
Amazon DocumentDB FIPS mendukung 140-3 endpoint dimulai dengan Amazon DocumentDB 5.0 (versi engine 3.0.3727) cluster di wilayah ini: ca-central-1, us-west-2, us-east-1, us-east-1, us-east-2, us-east-2, -1. us-gov-east us-gov-west
-
Setelah menentukan nilai dari parameter tls
Anda, lanjutkan menghubungkan ke klaster Anda dengan menggunakan salah satu contoh kode di bagian berikut.
Menghubungkan dengan TLS diaktifkan
Untuk melihat contoh kode untuk menghubungkan secara terprogram ke klaster Amazon TLS DocumentDB yang diaktifkan, pilih tab yang sesuai untuk bahasa yang ingin Anda gunakan.
Untuk mengenkripsi data dalam perjalanan, unduh kunci publik untuk Amazon global-bundle.pem
DocumentDB bernama menggunakan operasi berikut.
wget https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem
Jika aplikasi Anda ada di Microsoft Windows dan memerlukan PKCS7 file, Anda dapat mengunduh bundel PKCS7 sertifikat. Bundel ini berisi sertifikat perantara dan root di https://truststore.pki.rds.amazonaws.com/global/global-bundle.p7b
- Python
-
Kode berikut menunjukkan cara terhubung ke Amazon DocumentDB menggunakan TLS Python saat diaktifkan.
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
-
Kode berikut menunjukkan cara menyambung ke Amazon DocumentDB menggunakan TLS Node.js saat diaktifkan.
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
-
Kode berikut menunjukkan cara terhubung ke Amazon PHP TLS DocumentDB menggunakan saat diaktifkan.
<?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
-
Kode berikut menunjukkan cara terhubung ke Amazon DocumentDB menggunakan TLS Go saat diaktifkan.
catatan
Pada versi 1.2.1, Driver MongoDB Go hanya akan menggunakan sertifikat server CA pertama yang ditemukan di
sslcertificateauthorityfile
. Contoh kode di bawah ini membahas batasan ini dengan menambahkan secara manual semua sertifikat server yang ditemukansslcertificateauthorityfile
ke TLS konfigurasi khusus yang digunakan selama pembuatan klien.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
-
Saat menyambungkan ke klaster Amazon DocumentDB yang TLS diaktifkan dari aplikasi Java, program Anda harus AWS menggunakan file otoritas sertifikat (CA) yang disediakan untuk memvalidasi koneksi. Untuk menggunakan sertifikat Amazon RDS CA, lakukan hal berikut:
-
Unduh file Amazon RDS CA dari https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem
. -
Buat penyimpanan kepercayaan dengan sertifikat CA yang terdapat dalam file dengan melakukan perintah berikut. Pastikan untuk mengubah
<truststorePassword>
untuk sesuatu yang lain. Jika Anda mengakses penyimpanan kepercayaan yang berisi sertifikat CA lama (rds-ca-2015-root.pem
) dan sertifikat CA baru (rds-ca-2019-root.pem
), Anda dapat mengimpor paket sertifikat ke dalam penyimpanan kepercayaan.Berikut adalah contoh skrip shell yang mengimpor paket sertifikat ke trust store di sistem operasi Linux. Dalam contoh berikut, ganti masing-masing
user input placeholder
dengan informasi Anda sendiri. Terutama, di mana pun direktori contoh”mydir
“terletak di skrip, ganti dengan direktori yang Anda buat untuk tugas ini.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'" doneBerikut adalah contoh skrip shell yang mengimpor paket sertifikat ke trust store di sistem operasi macOS.
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 -
Gunakan
keystore
di program Anda dengan mengatur properti sistem berikut di aplikasi Anda sebelum membuat koneksi ke klaster Amazon DocumentDB.javax.net.ssl.trustStore:
<truststore>
javax.net.ssl.trustStorePassword:<truststorePassword>
-
Kode berikut menunjukkan cara terhubung ke Amazon DocumentDB menggunakan TLS Java saat diaktifkan.
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
-
Kode berikut menunjukkan cara terhubung ke Amazon DocumentDB menggunakan C #/. NETkapan TLS diaktifkan.
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
-
Kode berikut menunjukkan cara menghubungkan ke dan kueri Amazon DocumentDB menggunakan shell TLS mongo saat diaktifkan.
-
Terhubung ke Amazon DocumentDB dengan shell mongo. Jika Anda menggunakan versi shell mongo lebih awal dari 4.2, gunakan kode berikut untuk menghubungkan.
mongo --ssl --host sample-cluster.node.us-east-1.docdb.amazonaws.com:27017 --sslCAFile global-bundle.pem --username
<sample-user>
--password<password>
Jika Anda menggunakan versi yang sama dengan atau lebih besar dari 4.2, gunakan kode berikut untuk menghubungkan. Tulisan yang dapat dicoba ulang tidak didukung di AWS DocumentDB. Jika Anda menggunakan shell mongo lama (bukan mongosh), jangan sertakan
retryWrites=false
perintah dalam string kode apa pun. Secara default, penulisan yang dapat dicoba ulang dinonaktifkan. TermasukretryWrites=false
dapat menyebabkan kegagalan dalam perintah baca normal.mongo --tls --host sample-cluster.node.us-east-1.docdb.amazonaws.com:27017 --tlsCAFile global-bundle.pem --username
<sample-user>
--password<password>
-
Masukkan dokumen tunggal.
db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
-
Temukan dokumen yang sebelumnya dimasukkan.
db.myTestCollection.find({'hello':'Amazon DocumentDB'})
-
- R
-
Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB dengan R https://jeroen.github.io/mongolite/
menggunakan TLS mongolite () saat diaktifkan. #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
-
Kode berikut menunjukkan cara terhubung ke Amazon DocumentDB dengan TLS Ruby saat diaktifkan.
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
Menghubungkan dengan TLS dinonaktifkan
Untuk melihat contoh kode untuk menghubungkan secara terprogram ke klaster Amazon TLS DocumentDB -disabled, pilih tab untuk bahasa yang ingin Anda gunakan.
- Python
-
Kode berikut menunjukkan cara terhubung ke Amazon DocumentDB menggunakan TLS Python saat dinonaktifkan.
## 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
-
Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB menggunakan TLS Node.js saat dinonaktifkan.
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
-
Kode berikut menunjukkan cara terhubung ke Amazon PHP TLS DocumentDB menggunakan kapan dinonaktifkan.
<?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
-
Kode berikut menunjukkan cara terhubung ke Amazon DocumentDB menggunakan TLS Go saat dinonaktifkan.
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
-
Kode berikut menunjukkan cara terhubung ke Amazon DocumentDB menggunakan TLS Java saat dinonaktifkan.
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
-
Kode berikut menunjukkan cara terhubung ke Amazon DocumentDB menggunakan C #/. NETkapan TLS dinonaktifkan.
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
-
Kode berikut menunjukkan cara menghubungkan ke dan kueri Amazon DocumentDB menggunakan shell TLS mongo saat dinonaktifkan.
-
Terhubung ke Amazon DocumentDB dengan shell mongo.
mongo --host
mycluster.node.us-east-1
.docdb.amazonaws.com:27017 --username<sample-user>
--password<password>
-
Masukkan dokumen tunggal.
db.myTestCollection.insertOne({'hello':'Amazon DocumentDB'})
-
Temukan dokumen yang sebelumnya dimasukkan.
db.myTestCollection.find({'hello':'Amazon DocumentDB'})
-
- R
-
Kode berikut menunjukkan cara menghubungkan ke Amazon DocumentDB dengan R https://jeroen.github.io/mongolite/
menggunakan TLS mongolite () saat dinonaktifkan. #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
-
Kode berikut menunjukkan cara terhubung ke Amazon DocumentDB dengan TLS Ruby saat dinonaktifkan.
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