Connect Using Python

You’ll now connect to the Amazon DocumentDB cluster using python client i.e. pymongo.

Make sure you have exited the Mongo Shell <Ctrl-C> and are at the Linux command line for these next steps.

Download the sample python code from below repository.

wget https://raw.githubusercontent.com/aws-samples/amazon-documentdb-samples/master/samples/connect-and-query/sample_python_documentdb.py

Install pymongo client in your AWS Cloud9 envrionment.

sudo pip install pymongo

Review the sample_python_documentdb.py. The sample code creates a connection to Amazon DocumentDB cluster and performs an insert operation to write few documents to Amazon DocumentDB, finds a document using one of the attributes in JSON and then updates the value of this document.

Navigate to the Amazon DocumentDB console and locate your cluster using the cluster identifier. Click on the cluster identifier link and choose Configuration Tab on the Clusters menu to find the Cluster Endpoint to retrieve your cluster’s connection string. Then use this value and the userid and password for your cluster to set Linux environment variables in Cloud9 that are required to initiate a connection from the python client.

export clusterendpoint=<YOUR CLUSTER HOST NAME FROM CONNECTION STRING>:27017

Now export username

export username=<YOUR USERNAME>

And then password

export password=<YOUR PASSWORD>

(Alternatively, you can store your password and other DocumentDB cluster credentials securely in Secrets Manager for the Python application to access your DocumentDB cluster. This capability is covered in the Security lab module.)

Execute the code and examine the output

python sample_python_documentdb.py

The console statements indicate the code execution flow.

Successfully inserted data
Printing query results
{'_id': 4, 'name': 'Jesse', 'status': 'active', 'level': 3, 'score': 27}
Updating document
{'_id': 4, 'name': 'Jesse', 'status': 'active', 'level': 4, 'score': 27}

Congratulations! You have completed the CRUD operations lab. Proceed to next section to scale the Amazon DocumentDB cluster.