Python中使用pymongo与MongoDB交互指南pymongo是Python操作MongoDB数据库的核心驱动库,通过以下步骤可以高效完成数据库交互:
1. 安装与基础配置
2. 数据库操作核心方法
数据库与集合选择db = client['mydatabase'] # 选择/创建数据库collection = db['mycollection'] # 选择/创建集合文档插入- 单条插入:document = {"name": "John Doe", "age": 30}result = collection.insert_one(document)print(f"插入ID: {result.inserted_id}")
- 批量插入:documents = [ {"name": "Alice", "age": 25}, {"name": "Bob", "age": 35}]result = collection.insert_many(documents)print(f"插入ID列表: {result.inserted_ids}")
数据查询- 基础查询:# 查询age>25且name以"Doe"结尾的文档query = {"age": {"$gt": 25}, "name": {"$regex": "Doe$"}}results = collection.find(query)for doc in results: print(doc)
- 查询修饰符:# 限制返回字段collection.find({}, {"name": 1, "_id": 0}) # 只返回name字段# 分页查询collection.find().skip(10).limit(5) # 跳过10条,返回5条
聚合操作pipeline = [ {"$group": {"_id": "$age", "count": {"$sum": 1}}}, {"$sort": {"_id": 1}}]results = collection.aggregate(pipeline)for result in results: print(f"年龄: {result['_id']}, 人数: {result['count']}")3. 性能优化技巧
批量操作- 批量插入比单条插入性能提升3-5倍
- 批量更新示例:bulk_ops = [ UpdateOne({"name": "Alice"}, {"$set": {"age": 26}}), UpdateOne({"name": "Bob"}, {"$set": {"age": 36}})]collection.bulk_write(bulk_ops)
索引管理# 创建单字段索引collection.create_index([("name", pymongo.ASCENDING)])# 创建复合索引collection.create_index([("age", pymongo.ASCENDING), ("name", pymongo.DESCENDING)])# 查看索引print(collection.list_indexes())4. 错误处理与最佳实践
异常处理from pymongo.errors import ConnectionFailure, OperationFailuretry: client = MongoClient('mongodb://localhost:27017/') client.admin.command('ping') # 测试连接except ConnectionFailure as e: print(f"连接失败: {e}")except OperationFailure as e: print(f"操作失败: {e}")连接池管理- 默认启用连接池(最大100个连接)
- 手动配置示例:client = MongoClient( 'mongodb://localhost:27017/', maxPoolSize=50, minPoolSize=10, waitQueueTimeoutMS=2500)
5. 常见问题解决方案
连接问题排查- 检查MongoDB服务状态:systemctl status mongod
- 验证网络连通性:telnet localhost 27017
- 检查认证配置:client = MongoClient( 'mongodb://user:pass@localhost:27017/', authSource='admin', authMechanism='SCRAM-SHA-256')
查询性能优化- 使用explain()分析查询:print(collection.find({"age": {"$gt": 25}}).explain("executionStats"))
- 避免全表扫描:确保查询字段有索引
重复键错误处理try: collection.insert_one({"_id": 1, "name": "Test"})except pymongo.errors.DuplicateKeyError: print("文档ID已存在") # 更新已存在文档 collection.update_one({"_id": 1}, {"$set": {"name": "Updated"}})通过系统掌握这些核心操作和优化技巧,可以高效完成MongoDB数据库开发任务。建议结合实际项目需求,逐步实践索引优化、聚合管道设计等高级功能。