from pymongo import MongoClient
# 创建MongoClient对象,连接到MongoDB服务器
client = MongoClient('mongodb://localhost:27017/')
# 选择数据库
db = client['mydatabase']
# 选择集合(类似于关系型数据库中的表)
collection = db['mycollection']
# 插入文档
post = {"author": "Mike", "text": "My first blog post!"}
posts = db.posts
post_id = posts.insert_one(post).inserted_id
print(f"Inserted post ID: {post_id}")
# 查询文档
result = posts.find_one({"author": "Mike"})
print(f"Found post: {result}")
# 更新文档
posts.update_one({"author": "Mike"}, {"$set": {"text": "Updated blog post!"}})
# 删除文档
posts.delete_one({"author": "Mike"})
# 关闭连接
client.close()
pymongo 库来与 MongoDB 进行交互。MongoClient 对象连接到本地的 MongoDB 服务器。insert_one 方法插入一个文档,并获取插入的文档 ID。find_one 方法根据条件查询单个文档。update_one 方法根据条件更新文档内容。delete_one 方法根据条件删除文档。上一篇:编写python程序的步骤
下一篇:pythonround函数用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站