MongoDB 数据库的基本 Python 代码示例

确保已经安装了 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()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值