Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pymongo not able to retrieve files

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

like image 819
Ninad Mhatre Avatar asked Jul 31 '14 18:07

Ninad Mhatre


People also ask

How do I get all files in collection PyMongo?

To get all the Documents of the Collection use find() method. The find() method takes a query object as a parameter if we want to find all documents then pass none in the find() method.

Is PyMongo blocked?

Tornado is an asynchronous Python web framework, and PyMongo is a blocking driver for MongoDB. Obviously, any lengthy PyMongo operation blocks the event loop and hobbles its throughput.

How do I find a document in PyMongo?

The find_One() method of pymongo is used to retrieve a single document based on your query, in case of no matches this method returns nothing and if you doesn't use any query it returns the first document of the collection.

Is PyMongo thread safe?

PyMongo is thread-safe and even provides built-in connection pooling for threaded applications.


1 Answers

You need to import the ObjectId symbol:

from bson import ObjectId

Then your code should work.

like image 134
A. Jesse Jiryu Davis Avatar answered Nov 05 '22 20:11

A. Jesse Jiryu Davis