安装 MongoDB 驱动:
在 Python 中使用 MongoDB,首先需要安装 pymongo
驱动。可以使用以下命令进行安装:
pip install pymongo
连接数据库:
使用 pymongo
建立与 MongoDB 数据库的连接,包括连接字符串、认证等配置。示例代码如下:
from pymongo import MongoClient
# 连接 MongoDB 服务器
client = MongoClient("mongodb://localhost:27017/")
# 连接数据库
db = client["mydatabase"]
操作数据库和集合:
- 创建/选择数据库:使用
client["databasename"]
或client.databasename
。 - 创建/选择集合:使用
db["collectionname"]
或db.collectionname
。
增删改查操作:
1.插入数据:使用 insert_one()
或 insert_many()
方法向集合中插入数据。示例代码如下:
# 插入单个文档
data = {"name": "John", "age": 25}
collection.insert_one(data)
# 插入多个文档
data_list = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 35}
]
collection.insert_many(data_list)
2.查询数据:使用 find()
方法进行查询,可以添加条件、投影等操作。示例代码如下:
# 查询所有文档
result = collection.find()
for document in result:
print(document)
# 条件查询
result = collection.find({"age": {"$gt": 30}})
3.更新数据:使用 update_one()
、update_many()
方法更新数据。示例代码如下:
# 更新单个文档
collection.update_one({"name": "John"}, {"$set": {"age": 26}})
# 更新多个文档
collection.update_many({"age": {"$lt": 30}}, {"$inc": {"age": 1}})
4.删除数据:
使用 delete_one()
、delete_many()
方法删除数据。示例代码如下:
# 删除单个文档
collection.delete_one({"name": "John"})
# 删除多个文档
collection.delete_many({"age": {"$gt": 30}})
索引:
在 MongoDB 中,索引可以提高查询性能。可以使用 create_index()
方法创建索引。示例代码如下:
# 创建单字段索引
collection.create_index("name")
# 创建复合索引
collection.create_index([("name", pymongo.ASCENDING), ("age", pymongo.DESCENDING)])
聚合操作:
MongoDB 支持聚合管道操作,可以对数据进行多个阶段的处理和转换。示例代码如下:
# 聚合操作示例
pipeline = [
{"$match": {"age": {"$gt": 30}}},
{"$group": {"_id": "$name", "count": {"$sum": 1}}}
]
result = collection.aggregate(pipeline)
文件存储:
MongoDB 可以存储文件(如图片、视频等),可以使用 GridFS 进行文件的存储和检索。示例代码如下:
# 存储文件
with open("image.jpg", "rb") as file:
content = file.read()
client.fs.files.insert_one({
"filename": "image.jpg",
"contentType": "image/jpeg",
"content": content
})
# 检索文件
file = client.fs.files.find_one({"filename": "image.jpg"})
content = file["content"]
with open("downloaded_image.jpg", "wb") as file:
file.write(content)
结尾:
这些是 Python 中使用 MongoDB 的基本知识体系和一些代码案例,希望对你有所帮助。根据实际需求,你可以深入学习和探索更多 MongoDB 的功能和用法。