0

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?

Qing Yong
  • 127
  • 3
  • 15

1 Answers1

0

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  
hassansin
  • 16,918
  • 3
  • 43
  • 49
  • what's the error message? does it say `with _id '5590c2a71d41c81703458433'` or `with _id ObjectId('5590c2a71d41c81703458433')`? – hassansin Jun 29 '15 at 08:35
  • sorry my bad. the id was wrong. it's working now but why my printout is like this: 74�>տ����k�ܿ���,X��?+���Rg�>����߿bk� ? – Qing Yong Jun 29 '15 at 09:19
  • That's encoding issue. Try setting encoding to utf8 before printing. – hassansin Jun 29 '15 at 12:14