这是预期的结果。原因是您在插入(放置)期间没有为字段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 返回一个“文件名”值列表。