python 操作mongodb 文件相关

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"))









猜你喜欢

转载自www.cnblogs.com/ericblog1992/p/11422665.html
今日推荐