gridfs "list" 方法 returns 具有非空集合的空列表

The gridfs "list" method returns empty list with non empty collection

我们可以使用 PyMongo 而不是使用列表函数来获取存储在 GridFS 中的文件数吗?

此外,当我在 gridfs 下尝试 list() 方法时,它给了我一个空列表,尽管数据库中有文件。能够使用 _id 使用 get() 方法检索文件。 如果我们保存没有文件名的文件并依赖于 _id 值,list() 函数是否 return 列出存储在 gridfs db 下的所有文件。

代码:

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'''

这是预期的结果。原因是你没有为字段 filename during insert (put), however the list method returns distinct values for the filename field in the collection. So it returns empty list if the field doesn't exist in the collection. 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 returns 'filename' 个值的列表。