确保已经安装了 pymongo 库。如果没有安装,可以使用以下命令安装:
pip install pymongo
接下来是连接 MongoDB 数据库的示例代码:
from pymongo import MongoClient
# MongoDB 连接信息
mongodb_host = 'localhost' # MongoDB 主机
mongodb_port = 27017 # MongoDB 端口
database_name = 'mydatabase' # 数据库名称
collection_name = 'mycollection' # 集合(表)名称
# 建立 MongoDB 客户端
client = MongoClient(mongodb_host, mongodb_port)
# 获取数据库
db = client[database_name]
# 获取集合
collection = db[collection_name]
# 插入文档到集合中
data = {
"name": "John",
"age": 30,
"city": "New York"
}
result = collection.insert_one(data)
print(f"插入的文档 ID: {result.inserted_id}")
# 查询集合中的文档
query = {"name": "John"}
document = collection.find_one(query)
if document:
print(f"查询到的文档: {document}")
else:
print("未找到文档.")
# 更新集合中的文档
update_query = {"name": "John"}
update_data = {"$set": {"city": "San Francisco"}}
update_result = collection.update_one(update_query, update_data)
print(f"修改了 {update_result.modified_count} 个文档")
# 删除集合中的文档
delete_query = {"name": "John"}
delete_result = collection.delete_one(delete_query)
print(f"删除了 {delete_result.deleted_count} 个文档")
# 关闭 MongoDB 客户端连接
client.close()