以下是一个完整的使用Python操作MongoDB的示例代码,包括连接数据库、插入文档、查询文档、更新文档和删除文档等操作:
from pymongo import MongoClient
# 连接数据库
client = MongoClient("mongodb://localhost:27017/")
database = client["mydatabase"]
collection = database["mycollection"]
# 插入文档
document = {"name": "John", "age": 30}
collection.insert_one(document)
# 查询文档
document = collection.find_one()
print(document)
# 更新文档
query = {"name": "John"}
new_values = {"$set": {"age": 40}}
collection.update_one(query, new_values)
# 查询更新后的文档
updated_document = collection.find_one({"name": "John"})
print(updated_document)
# 删除文档
query = {"name": "John"}
collection.delete_one(query)
# 查询删除后的文档
deleted_document = collection.find_one({"name": "John"})
print(deleted_document)
# 插入多个文档
documents = [
{"name": "Mike", "age": 25},
{"name": "Sarah", "age": 35},
{"name": "Tom", "age": 45}
]
collection.insert_many(documents)
# 查询年龄大于30的文档并按照名字升序排序
cursor = collection.find({"age": {"$gt": 30}}).sort("name")
# 遍历查询结果
for document in cursor:
print(document)
在上面的示例代码中,我们首先使用MongoClient()方法连接到MongoDB数据库,并指定了要使用的数据库和集合。然后,我们插入了一个文档,查询了这个文档,更新了这个文档,删除了这个文档,插入了多个文档,并使用过滤器和排序器查询了多个文档。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。