Question

I am playing around with mongodb (GridFS) to store files (zip) and try to retrieve them using python`s "pymongo" but its not working as expected i am not able to understand how to retrieve the file(s) i have addedd ...

Below is the code i ran from IDLE ( Python 3.4.1 )

>>> db = Connection(port=31000, host="localhost").fs
>>> db.name
'fs'
>>> db.validate_collection
<bound method Database.validate_collection of Database(Connection('localhost', 31000), 'fs')>
>>> blob_store = gridfs.GridFS(db, collection='bstore')
>>> local_db = dict()
>>> k = r'd:\test\my-scripts.zip'
>>> local_db[k] = blob_store.put(open(k, 'rb'))

[** File is saved, i checked using robomongo **]

>>> blob_store.exists(filename=k)
False
>>> blob_store.exists("53da7cb1b3b44b13e0e27721")
False
>>> local_db
{'d:\\test\\my-scripts.zip': ObjectId('53da7cb1b3b44b13e0e27721')}
>>> blob_store.list()
[]
>>> b = gridfs.GridFS(db, collection='bstore.files')
>>> b.list()
[]
>>> x = blob_store.get(Objectid("53da7cb1b3b44b13e0e27721"))
Traceback (most recent call last):
 File "<pyshell#20>", line 1, in <module>
 x = blob_store.get(Objectid("53da7cb1b3b44b13e0e27721"))
NameError: name 'Objectid' is not defined
>>> local_db
{'d:\\test\\my-scripts.zip': ObjectId('53da7fd0b3b44b13e0e2772a')}
>>> blob_store.find()
<gridfs.grid_file.GridOutCursor object at 0x0000000003DC1828>
>>> a = blob_store.find(ObjectId("53da7fd0b3b44b13e0e2772a"))
Traceback (most recent call last):
   File "<pyshell#29>", line 1, in <module>
   a = blob_store.find(ObjectId("53da7fd0b3b44b13e0e2772a"))
NameError: name 'ObjectId' is not defined

Now i am not sure how to retrieve the file from mongo? am i missing something obvious?

Thanks

Was it helpful?

Solution

You need to import the ObjectId symbol:

from bson import ObjectId

Then your code should work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top