安装pymongo
pip install pymongo
使用SSL证书连接
from pymongo import MongoClient
import ssl
# 指定文档数据库的连接URI
uri = "mongodb://username:password@hostname:port/database_name?ssl=true&authSource=admin"
# 创建SSL上下文
context = ssl.create_default_context(cafile="/path/to/ca.pem")
context.load_cert_chain("/path/to/client.pem", keyfile="/path/to/client.key")
# 创建客户端
client = MongoClient(uri, ssl_certfile="/path/to/client.pem", ssl_keyfile="/path/to/client.key", ssl_ca_certs="/path/to/ca.pem", ssl_cert_reqs=ssl.CERT_REQUIRED, ssl_context=context)
# 获取数据库实例
database = client["testdb"]
# 获取集合实例
collection = database["testcollection"]
# 插入文档
document = {"name": "John Doe", "age": 30, "email": "johndoe@example.com"}
collection.insert_one(document)
# 查询文档
query = {"name": "John Doe"}
result = collection.find_one(query)
print(result)
# 关闭连接
client.close()
无证书连接
from pymongo import MongoClient
# 指定数据库的连接URI
uri = "mongodb://username:password@hostname:port/database_name?authSource=admin"
# 创建客户端
client = MongoClient(uri)
# 获取数据库实例
database = client["testdb"]
# 获取集合实例
collection = database["testcollection"]
# 插入文档
document = {"name": "John Doe", "age": 30, "email": "johndoe@example.com"}
collection.insert_one(document)
# 查询文档
query = {"name": "John Doe"}
result = collection.find_one(query)
print(result)
# 关闭连接
client.close()