Connecting to an Amazon DocumentDB Global Cluster

You will connect to global clusters using the cluster endpoint of the primary cluster for writes and reads from primary region. You will connect to global clusters using the cluster endpoint of the secondary cluster(s) for reads from the secondary region(s).

When you view an Amazon DocumentDB global cluster in the console, you can see endpoints associated with all of its clusters. The following screenshot shows an example.

Primary Region

Connect to Amazon DocumentDB primary cluster:

Note: Execute below commands in the primary region Cloud9 IDE.

mongo --quiet --ssl --host $docdbEndpoint:27017 --sslCAFile rds-combined-ca-bundle.pem --username $docdbUser --password $docdbPass

Insert documents in primary region

var data=[];
for (var i=1000000; i<1000004; i++){
	var doc = {
		"_id": NumberLong(i),
		"createDate": new Date()
	};
	data.push(doc);
}

db.getSiblingDB("sampledb").test.insertMany(data);

The output for this query retuns the _id of the documents inserted.

{
        "acknowledged" : true,
        "insertedIds" : [
                NumberLong(1000000),
                NumberLong(1000001),
                NumberLong(1000002),
                NumberLong(1000003)
        ]
}

For cross region, read only traffic, you will connect to one your secondary clusters. We recommend that you connect to your secondary cluster using the cluster endpoint in replica set mode. Since all instances are read-only replica instances, read preference setting can be ignored. To minimize latency, choose whichever reader endpoint is in your region or the region closest to you.

Connect to Amazon DocumentDB secondary cluster:

Note: Execute below commands in the secondary region Cloud9 IDE.

export secondary_region_clusterendpoint=`aws docdb describe-db-clusters --query "DBClusters[*].ReaderEndpoint" --output text`
mongo --quiet --ssl --host $secondary_region_clusterendpoint:27017 --sslCAFile rds-combined-ca-bundle.pem --username $docdbUser --password $docdbPass

Reading documents from secondary region

Use the below query to read data inserted to Amazon DocumentDB. The find API takes a filter criteria and returns the document matching the criteria. You can optionally use pretty() to pretty print the output.

rs.secondaryOk();
db.getSiblingDB("sampledb").test.find({"_id": NumberLong(1000000)}).pretty();

The matched document is returned as the output of the above query.

{
        "_id" : NumberLong(1000000),
        "createDate" : ISODate("2021-06-14T19:44:25.446Z")
}