Connect Using Python

You will now connect to the Amazon DocumentDB cluster using the PyMongo distribution for interacting with your DocumentDB cluster from Python.

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 using the command below.

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

Review the Python code in sample_python_documentdb.py by viewing from the command line or by double-clicking the file in the AWS Cloud9 file browser.

Review Python Code

The sample code creates a connection to Amazon DocumentDB cluster using environment variables, inserts several documents to Amazon DocumentDB, finds a document using one of the attributes in JSON, and then updates the value of this document.

A best practice is to store database credentials in Secrets Manager. This capability is covered later in the Security lab.

Execute the code and examine the output

python sample_python_documentdb.py

The console statements indicate the code execution flow.

Amazon DocumentDB Client App 1

Congratulations! You have completed the CRUD operations lab.