Python3操作MongoDB实战指南,C++多态。
·
Python3 MongoDB 使用指南
安装与驱动配置
确保系统已安装Python3和MongoDB数据库。通过pip安装官方驱动pymongo:
pip install pymongo
导入模块并建立连接:
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/") # 默认端口
db = client["example_db"] # 数据库名称
collection = db["example_collection"] # 集合名称
基本CRUD操作
插入单条文档:
document = {"name": "Alice", "age": 25, "skills": ["Python", "MongoDB"]}
insert_result = collection.insert_one(document)
print(insert_result.inserted_id) # 输出生成的ObjectId
批量插入文档:
documents = [
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 35}
]
result = collection.insert_many(documents)
查询文档:
# 查询单条
user = collection.find_one({"name": "Alice"})
# 条件查询
users = collection.find({"age": {"$gt": 25}}) # 年龄大于25
for u in users:
print(u)
更新文档:
# 更新单条
collection.update_one({"name": "Alice"}, {"$set": {"age": 26}})
# 批量更新
collection.update_many({"age": {"$lt": 30}}, {"$inc": {"age": 1}}) # 年龄+1
删除文档:
collection.delete_one({"name": "Bob"}) # 删除单条
collection.delete_many({"age": {"$gt": 40}}) # 批量删除
高级查询技巧
复合条件查询:
# AND条件
results = collection.find({"age": {"$gte": 20}, "name": {"$regex": "^A"}})
# OR条件
from pymongo import MongoClient
query = {"$or": [{"age": {"$lt": 25}}, {"name": "Bob"}]}
results = collection.find(query)
聚合管道:
pipeline = [
{"$match": {"age": {"$gt": 20}}},
{"$group": {"_id": None, "avg_age": {"$avg": "$age"}}}
]
agg_result = list(collection.aggregate(pipeline))
索引优化
创建索引提升查询性能:
# 单字段索引
collection.create_index("name")
# 复合索引
collection.create_index([("name", 1), ("age", -1)])
# 查看现有索引
print(collection.index_information())
事务管理
多文档事务处理(需MongoDB 4.0+):
with client.start_session() as session:
try:
with session.start_transaction():
collection.insert_one({"name": "Dave"}, session=session)
collection.update_one({"name": "Alice"}, {"$set": {"status": "active"}}, session=session)
except Exception as e:
session.abort_transaction()
print("Transaction aborted:", e)
性能监控
添加性能监控钩子:
from pymongo import monitoring
class CommandLogger(monitoring.CommandListener):
def started(self, event):
print(f"Command {event.command_name} started")
monitoring.register(CommandLogger())
最佳实践
- 使用连接池管理数据库连接
- 合理设计文档结构避免嵌套过深
- 批量操作时优先考虑
bulk_write - 生产环境启用身份验证和SSL加密
- 定期执行
compact命令回收磁盘空间
该指南覆盖了Python3操作MongoDB的核心功能,实际开发中应根据具体业务需求调整实现方式。
更多推荐


所有评论(0)