Using Python to Operate Amazon DocumentDB
To use Python to operate Amazon DocumentDB database connections, insert, query, modify, and delete data, you need to install the 'pymongo' and 'boto3' class libraries. The following is an example Python code for operating Amazon DocumentDB:
1. Connect to the Amazon DocumentDB database:
python
import pymongo
import ssl
#Set connection parameters
client = pymongo.MongoClient("<cluster_endpoint>", ssl_cert_reqs=ssl.CERT_NONE)
#Create Database
db = client["mydatabase"]
#Create Collection
collection = db["mycollection"]
2. Insert data:
python
#Insert a document
document = {"name": "John", "age": 30}
collection.insert_one(document)
#Insert multiple documents
documents = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 35}
]
collection.insert_many(documents)
3. Query data:
python
#Query all documents
result = collection.find()
for document in result:
print(document)
#Query documents with specific criteria
result = collection.find({"name": "John"})
for document in result:
print(document)
4. Modify data:
python
#Modify the first document that meets the criteria
collection.update_one({"name": "John"}, {"$set": {"age": 40}})
#Modify all documents that meet the criteria
collection.update_many({"name": "John"}, {"$set": {"age": 40}})
5. Delete data:
python
#Delete the first document that meets the criteria
collection.delete_one({"name": "John"})
#Delete all eligible documents
collection.delete_many({"name": "John"})
Attention:<cluster_ Endpoint>` needs to be replaced with the connection string of your Amazon DocumentDB cluster.
The above are some basic operation examples, and you can further explore the functions of the 'pymongo' and 'boto3' class libraries according to your own needs.