10

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

2 Answers 2

30

You need to import the ObjectId symbol:

from bson import ObjectId 

Then your code should work.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this works but I wonder why I wasn't included in the library all together.
1

You can import ObjectId using the following:

from bson.objectid import ObjectId 

Alternatively you can also do the following:

from bson import ObjectId 

If you are having trouble searching for the automatically created ObjectId. You can yourself write a new document(record/item) by providing value to "_id" key in insert_one or insert_many operation:

document = {"_id": "1001", "Name": "Mercedes", "Price": 4910000, "Track": "Motorsport"} collection.insert_one(document) 

or you can also create a document by giving your own Object Id to the document as follows:

document = {"_id": ObjectId('63ca647ccc17147000b7a312'), "Name": "Mercedes", "Price": 4910000, "Track": "Motorsport"} collection.insert_one(document) 

However, ObjectId() can only accept limited arguments which can be found on the MongoDb documentation

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.