Python 中操作 MongoDB gridfs
时间: 2024-03-28 22:14:46 浏览: 20
MongoDB GridFS 是一种用于存储大文件的机制,它将大文件分割成多个块,并将这些块存储在 MongoDB 的集合中。在 Python 中,可以使用 PyMongo 库来操作 MongoDB GridFS。
以下是使用 PyMongo 操作 MongoDB GridFS 的示例代码:
1. 连接 MongoDB 数据库
```python
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['mydatabase']
```
2. 获取 GridFS 对象
```python
from gridfs import GridFS
fs = GridFS(db)
```
3. 上传文件
```python
with open('large_file.txt', 'rb') as f:
fs.put(f, filename='large_file.txt')
```
4. 下载文件
```python
with open('downloaded_file.txt', 'wb') as f:
f.write(fs.get_last_version('large_file.txt').read())
```
5. 删除文件
```python
fs.delete(fs.get_last_version('large_file.txt')._id)
```
以上是 MongoDB GridFS 的基本操作,可以根据需要进行扩展和修改。