0

I had uploaded some PDF, PNG files to a local instance of mongodb. By mistake I deleted these files and I can no longer recover them using the regular recover options. However, they are in my local mongodb database. How can I save them back in their original format on my computer?

I know the following:

import pymongo as pym
import gridfs

def connectToDb():
    client = pym.MongoClient('mongodb://localhost:27017/')
    db = client.questionbank
    collectn = db.questionbank
    fs = gridfs.GridFS(db)
    return db, collectn, fs

db, collectn, fs = connectToDb()

filelist = list( db.fs.files.find({}, {"_id": 1, "filename": 1}) )
fileid = filelist[0]['_id']
fobj = fs.get(fileid)

## I don't know what to do after this. I think I cannot use read since I don't 
## want the string. I want to save the pdf file as a pdf file.

Any help will be greatly appreciated. Thanks in advance.

Curious2learn
  • 31,692
  • 43
  • 108
  • 125

2 Answers2

0

Okay, I figured this out on my own. It can be done in the following way:

To the above code add the lines:

f = open('tempfigfile.pdf', 'wb')
f.write(fobj.read())
f.close()

This saves the file as tempfigfile.pdf.

Curious2learn
  • 31,692
  • 43
  • 108
  • 125
0

This code will save all the files to ur local folder from mongodb gridfs.

i=0 
cursor=fs.find()
while(i < cursor.count()):
    fi=cursor.next()
    with open("C:\\localfolder\\"+fi.filename,"wb") as f:
        f.write(fi.read())
        f.closed
        i=i+1
Nags
  • 1
  • 2