pymongo无法检索文件

时间:2014-07-31 18:01:03

标签: mongodb pymongo gridfs python-3.4

我正在使用mongodb(GridFS)存储文件(zip)并尝试使用python`s" pymongo"来检索它们。但它没有按预期工作我无法理解如何检索我添加的文件......

以下是我从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

现在我不确定如何从mongo中检索文件?我错过了一些明显的东西吗?

由于

1 个答案:

答案 0 :(得分:15)

您需要导入ObjectId符号:

from bson import ObjectId

然后你的代码应该可以工作。