Trying to use fs.get function to get the chunks in mongoDB

1.4k views Asked by At

I am trying to get the files that are stored in mongoDB with GridFS.

I wrote this function to store the files into mongoDB using GridFS

def write_file_object(file_name):
with open(file_name) as mydoc:
    b = fs.put(mydoc, content_type="text/plain", filename="file")
    print b

and this function to get the files in mongoDB by passing the file ID which for this case is 5590c2a71d41c81703458433.

def get_file_object(file_id):
out = fs.get(file_id).read()
print out   

but I keep getting this error: gridfs.errors.NoFile: no file in gridfs collection Collection(Database(MongoClient('localhost', 27017), u'gridfs_example'), u'fs.files') with _id '5590c2a71d41c81703458433'

Any help to get the files? Is my method wrong?

1

There are 1 answers

3
hassansin On

You need to convert the id string to ObjectId:

from bson.objectid import ObjectId

def get_file_object(file_id):
  out = fs.get(ObjectId(file_id)).read()
  print out