使用python操作DocumentDB

下载示例代码:

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

安装pymongo依赖:

pip3 install pymongo

示例代码中数据库的用户名、密码、连接地址要进行替换:

import os
import sys
import pymongo

#Insert sample data
SEED_DATA = [
{ "_id" : 1, "name" : "Tim", "status": "active", "level": 12, "score":202},
{ "_id" : 2, "name" : "Justin", "status": "inactive", "level": 2, "score":9},
{ "_id" : 3, "name" : "Beth", "status": "active", "level": 7, "score":87},
{ "_id" : 4, "name" : "Jesse", "status": "active", "level": 3, "score":27}
]

#Get Amazon DocumentDB ceredentials from environment variables
username = "testuser"
password = "testpass"
clusterendpoint = "demo-documentdb.cluster-cpayj88cqtvo.us-west-2.docdb.amazonaws.com:27017"


def main(args):
    #Establish DocumentDB connection
    client = pymongo.MongoClient(clusterendpoint, username=username, password=password, tls='true', tlsCAFile='rds-combined-ca-bundle.pem',retryWrites='false')
    db = client.sample_database
    profiles = db['profiles']

    #Insert data
    profiles.insert_many(SEED_DATA)
    print("Successfully inserted data")

    #Find a document
    query = {'name': 'Jesse'}
    print("Printing query results")
    print(profiles.find_one(query))

    #Update a document
    print("Updating document")
    profiles.update(query, {'$set': {'level': 4}})
    print(profiles.find_one(query))

    # Clean up
    # db.drop_collection('profiles')
    client.close()

if __name__ == '__main__':
    main(sys.argv[1:])

示例代码首先建立与DocumentDB的连接,再插入几条document后进行查询操作,最后进行更新操作

执行python脚本:

python sample_python_documentdb.py

image-20211128130618034