https://api.mongodb.com/python/current/tutorial.html# 文档地址
from pymongo import MongoClient
from gridfs import *
client = MongoClient(host = "localhost", port=27017)
client.admin.authenticate("admin","abc123456")
db = client.school
gfs = GridFS(db, collection="book")
file = open("MongoDB与Python的交互.pdf","rb")
args = {"type":"PDF","keyword":"linux"}
gfs.put(file,filename = "MongoDB与Python的交互.pdf",**args)
file.close()
# 查询
book = gfs.find_one({"filename":"MongoDB与Python的交互.pdf"})
print(book.filename)
print(book.type)
print(book.keyword)
# 计算大小 M
print(math.ceil(book.length/1024/1024))
books = gfs.find({"type":"PDF"})
for one in books:
uploadDate = one.uploadDate + datetime.timedelta(hours = 8)
uploadDate = uploadDate.strftime("%Y-%M-%D %H:%M:%s")
print(one._id,one.filename, uploadDate)
查询文件是否存在
import math
import datetime
from bson.objectid import ObjectId
rs = gfs.exists(ObjectId("6d6500f276319f912b084b9e"))
print(rs)
rs = gfs.exists(**{"type":"PDF"})
print(rs)
文件获取
db = client.school
gfs = GridFS(db, collection="book")
document = gfs.get(ObjectId("5d6500f276319f912b084b9e"))
file=open("D:Linux手册.pdf","wb")
file.write(document.read())
file.close()
# 文件删除
gfs.delete(ObjectId("5d6500f276319f912b084b9e"))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。