You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python代码实现Google Colab与Amazon DocumentDB连接并插入字典数据

如何在Google Colab中用Python连接Amazon DocumentDB并存储字典

完全可以通过Google Colab的Python程序连接Amazon DocumentDB并存储字典,核心要解决网络连通性和认证配置问题,下面是具体步骤和排坑指南:

一、前置准备

  • 配置安全组:把Colab的公网IP加入DocumentDB集群所在安全组的入站规则(开放27017端口,TCP协议)。Colab的当前IP可以通过执行!curl ifconfig.me获取。
  • 下载CA证书:在Colab单元格里运行!wget https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem,获取DocumentDB的SSL证书。
  • 安装依赖库:执行!pip install pymongo,因为DocumentDB兼容MongoDB协议,用pymongo即可操作。

二、连接并插入字典的代码示例

from pymongo import MongoClient
import ssl

# 替换成你的DocumentDB集群信息
cluster_endpoint = "your-cluster-endpoint.docdb.amazonaws.com"
port = 27017
username = "your-db-username"
password = "your-db-password"
db_name = "test_db"
collection_name = "test_collection"

# 建立连接
client = MongoClient(
    cluster_endpoint,
    port=port,
    username=username,
    password=password,
    ssl=True,
    ssl_ca_certs='rds-combined-ca-bundle.pem',
    ssl_match_hostname=False  # 解决部分SSL主机名匹配失败问题
)

# 选择数据库和集合
db = client[db_name]
collection = db[collection_name]

# 要存储的字典
sample_dict = {
    "name": "Alice",
    "age": 28,
    "job": "Engineer",
    "skills": ["Python", "AWS"]
}

# 插入数据
insert_result = collection.insert_one(sample_dict)
print(f"插入成功,文档ID: {insert_result.inserted_id}")

# 验证插入结果
print("已插入的文档:")
print(collection.find_one({"_id": insert_result.inserted_id}))

三、常见连接失败排查

  • 安全组未放行IP:如果超时连接,先检查Colab的IP是否在安全组入站规则里,Colab的IP可能会变化,每次运行前最好重新获取并更新。
  • 证书错误:如果报SSL相关错误,确认证书文件已下载,路径正确。可以用!ls查看当前目录下是否有rds-combined-ca-bundle.pem。
  • 认证信息错误:核对用户名、密码、集群端点是否完全正确,DocumentDB不允许用root作为用户名,需提前创建有读写权限的数据库用户。
  • SSL主机名匹配失败:添加ssl_match_hostname=False参数即可解决,这是因为DocumentDB的SSL证书域名和集群端点可能存在不匹配的情况。

内容的提问来源于stack exchange,提问作者sourab maity

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 15:54:36