from pymongo import MongoClient
# 创建MongoClient连接对象,默认连接本地的MongoDB服务
client = MongoClient('mongodb://localhost:27017/')
# 获取或创建一个数据库,名称为mydatabase
db = client['mydatabase']
# 获取或创建一个集合(类似于关系型数据库中的表),名称为mycollection
collection = db['mycollection']
# 插入一条文档(类似于关系型数据库中的一行数据)
post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"]}
posts = collection.insert_one(post)
print(f"Inserted post ID: {posts.inserted_id}")
# 查询集合中的所有文档
for document in collection.find():
print(document)
# 根据条件查询文档
query_result = collection.find_one({"author": "Mike"})
print(f"Query result: {query_result}")
# 更新文档
update_result = collection.update_one({"author": "Mike"}, {"$set": {"text": "Updated blog post!"}})
print(f"Matched count: {update_result.matched_count}, Modified count: {update_result.modified_count}")
# 删除文档
delete_result = collection.delete_one({"author": "Mike"})
print(f"Deleted count: {delete_result.deleted_count}")
连接MongoDB:
MongoClient类来连接MongoDB服务器。默认情况下,它会连接到本地的MongoDB实例(localhost:27017)。选择数据库和集合:
client['mydatabase']选择或创建一个名为mydatabase的数据库。db['mycollection']选择或创建一个名为mycollection的集合。插入文档:
insert_one方法插入一条文档到集合中,并返回插入文档的ID。查询文档:
find方法查询集合中的所有文档,并遍历打印出来。find_one方法根据条件查询单个文档。更新文档:
update_one方法根据条件更新文档,并返回匹配和修改的文档数量。删除文档:
delete_one方法根据条件删除文档,并返回删除的文档数量。希望这段代码和解释对你有所帮助!
上一篇:python的内置函数
下一篇:python __new__
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站