python files related to the operation 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()

# Query 
book = gfs.find_one ({ "filename" : "MongoDB and Python interactive of.pdf"})
Print (book.filename)
Print (book.type)
Print (book.keyword)
# calculate the size 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()
 
# File deletion 
gfs.delete (ObjectId ( "5d6500f276319f912b084b9e") )









Guess you like

Origin www.cnblogs.com/ericblog1992/p/11422665.html