2016-05-17 65 views
2

除了使用list函數之外,我們可以使用PyMongo獲得存儲在GridFS中的文件數嗎?gridfs「list」方法返回非空集合的空列表

此外,當我嘗試gridfs下的list()方法時,它給了我一個空列表,儘管DB中有文件。能夠通過使用_id使用get()方法檢索文件。 如果我們保存沒有文件名的文件並且取決於_id值,list()函數是否返回存儲在gridfsdb下的所有文件的列表。

代碼:

client = pymongo.MongoClient(connect=False) 
grid_db = client['gridDB'] 
fs = gridfs.GridFS(grid_db) 
# Save an image 
img_identifier = fs.put(img, encoding="utf-8") 
# List the files stored 
print fs.list() 
'''[] Console shows empty array''' 

回答

1

這是預期的結果。原因是在插入(放入)過程中,您沒有爲字段filename設置值,但list方法返回集合中filename字段的值distinct。所以如果該字段不存在於集合中,它將返回空列表。 See the list() method implementation

def list(self): 
    """List the names of all files stored in this instance of 
    :class:`GridFS`. 
    .. versionchanged:: 3.1 
     ``list`` no longer ensures indexes. 
    """ 
    # With an index, distinct includes documents with no filename 
    # as None. 
    return [ 
     name for name in self.__files.distinct("filename") 
     if name is not None] 

演示:

>>> import pprint 
>>> from pymongo import MongoClient 
>>> import gridfs 
>>> client = MongoClient() 
>>> db = client.demo 
>>> fs = gridfs.GridFS(db) 
>>> fs.put('img.jpg', encoding='utf-8') 
ObjectId('573af0960acf4555437ceaa9') 
>>> fs.list() 
[] 
>>> pprint.pprint(db['fs.files'].find_one()) 
{'_id': ObjectId('573af0960acf4555437ceaa9'), 
'chunkSize': 261120, 
'encoding': 'utf-8', 
'length': 7, 
'md5': '82341a6c6f03e3af261a95ba81050c0a', 
'uploadDate': datetime.datetime(2016, 5, 17, 10, 21, 11, 38000)} 

正如你可以看到,現場filename不文檔中存在。現在,讓我們通過在filename說法:

>>> client.drop_database(db) # drop our demo database 
>>> fs.put('img.jpg', encoding='utf-8', filename='img.jpg') 
ObjectId('573af1740acf4555437ceaab') 
>>> fs.list() 
['img.jpg'] 
>>> pprint.pprint(db['fs.files'].find_one()) 
{'_id': ObjectId('573af1740acf4555437ceaab'), 
'chunkSize': 261120, 
'encoding': 'utf-8', 
'filename': 'img.jpg', 
'length': 7, 
'md5': '82341a6c6f03e3af261a95ba81050c0a', 
'uploadDate': datetime.datetime(2016, 5, 17, 10, 24, 53, 449000)} 

正如你所看到的,list返回「文件名」值的列表。